Linux Shell 03 条件测试

时间:2023-03-09 19:07:47
Linux Shell 03 条件测试

条件测试

方式一:在Bash中 test命令和[]是等价的。

  test命令:

if test $n1 -eq $n2
then
echo "The two number are equal"
fi

  []命令: "["后面和"]"前面有空格 

if [ $n1 -eq $n2 ]
then
echo "The two number are equal"
fi

方式二:(( expression )) 测试数学表达式结果

if ((n1 == n2)) 
then
echo "The two number are equal"
fi

  1. 常用的数学运算符:+,-,*,/,%,**(取幂),位移(<<,>>),++(自增),--(自减),& | ~(位逻辑运算),&& || !(逻辑运算)

  2. (())内部变量前可以不加$,内部不需要转义大小写"<,>"符号

  3. (())扩展了for, if, while测试运算, 使之支持C语言式语句,例如:

if (( n1 != n2)); then
...
fi for((i=; i<; i++))
do
...
done i=
while((i++<))
do
echo $i
done

方式三

  [[ expression ]] 支持字符串模式匹配

if [[ $user == roo* ]]
then
echo "hello $user"
fi