bash实现条件判断
条件测试类型:
1.整数测试
2.字符测试
3.文件测试
整数比较:
-eq 测试两个整数是否相等; 相等为真,不等为假
-ne:测试两个整数是否不等
-gt:测试一个数是否大于另一个整数
-lt: 测试一个数是否小于另一个数
-ge:大于或等于
-le: 小于或等于
文件测试表达式:[ express ] 或 [[ express]] 或text express
命令的间逻辑关系:
逻辑与:&&
逻辑或:| |
条件判断
if 判断条件;then
statement1
statement2
...
fi
if 判断条件;
then
statement1
statement2
...
else
statement3
statement4
...
fi
if 判断条件
then
command
command
...
elif 判断条件
then
command
...
else
command
fi
case 结构
case nem in
case1)
command
...
command;;
case2)
command
...
command;;
*)
command
...
command;;
例子:
1 #!/bin/bash
2
3 echo "please input a number:"
4 read number
5
6 if [ "$number" -lt 0 -o "$number" -gt 100 ]
7 then
8 echo "ERROR"
9 else
10 if [ "$number -ge 90" ]
11 then
12 echo "A"
13 else
14 echo "B"
15 fi
16 fi
17
注意:有一个错误的地方,在无论输入什么,出现的结果都是A,往大家能指教一下。
本文介绍如何使用Bash进行整数、字符及文件测试,并通过示例演示如何结合逻辑运算符进行复杂的条件判断。包括if-else语句的用法、case结构的应用,以及常见错误分析。
222

被折叠的 条评论
为什么被折叠?



