shell之条件判断
if条件
if command
then
commands
fi
if command
then
commands
else
commands
fi
if command1
then
commands
elif command2
then
more commands
fi
test命令
if-then语句不能测试命令退出状态码之外的条件。这时候我们要用test命令。如果test命令中列出的条件成立,test命令就会退出并返回退出状态码0。
#!/bin/bash
# Testing the test command
#
my_variable="Full"
#
if test $my_variable
then
echo "The $my_variable expression returns a True"
#
else
echo "The $my_variable expression returns a False"
fi
bash shell提供了另一种条件测试方法,无需在if-then语句中声明test命令。
if [ condition ]
then
commands
fi
数值比较
#!/bin/bash
var=5.5
if [ $var -eq 5 ]
then
echo "$var = 5"
else
echo "$var != 5"
fi
备注:我们不能在test命令中使用浮点值。否则,integer expression expected。bash shell只能处理整数。
字符串比较
大于号和小于号必须转义,否则shell会把它们当作重定向符号,把字符串值当作文件
名;
大于和小于顺序和sort命令所采用的不同。
-n和-z可以检查一个变量是否含有数据。
#!/bin/bash
val1=Testing
val2=testing
#
if [ $val1 \> $val2 ]
then
echo "$val1 is greater than $val2"
else
echo "$val1 is less than $val2"
fi
结果是:
Testing is less than testing
$ sort test
testing
Testing
在比较测试中,大写字母被认为是小于小写字母的。但sort命令恰好相反。当你将同样的
字符串放进文件中并用sort命令排序时,小写字母会先出现。这是由各个命令使用的排序技术不同造成的。
比较测试中使用的是标准的ASCII顺序,根据每个字符的ASCII数值来决定排序结果。sort命令使用的是系统的本地化语言设置中定义的排序顺序。对于英语,本地化设置指定了在排序顺序中小写字母出现在大写字母前。
文件比较
复合条件测试
[ condition1 ] && [ condition2 ]
[ condition1 ] || [ condition2 ]
使用双括号
双括号命令允许你在比较过程中使用高级数学表达式。test命令只能在比较中使用简单的算术操作。
(( expression ))
expression可以是任意的数学赋值或比较表达式。比如
注意,不需要将双括号中表达式里的大于号转义。这是双括号命令提供的另一个高级特性。
使用双方括号
[[ expression ]
双方括号命令提供了针对字符串比较的高级特性----模式匹配。
#!/bin/bash
if [[ $USER == o* ]]
then
echo "hello $USER"
else
echo "Sorry, $USER"
fi
case
case variable in
pattern1 | pattern2) commands1;;
pattern3) commands2;;
*) default commands;;
esac