1、if-then语句
(1)
if command
then
commands
fi
(2)
if command; then
commands
fi
eg:
if data
then
echo "it worked"
fi
备注:bash shell中如果命令的退出状态为0(执行成功),将执行then后面的所有指令。如果返回值非零,then后的指令将跳过。
2、if-then-else语句
if command
then
commands
else
commands
fi
3、嵌套if语句
if command1
then
commands
elif command2
then
more commands
fi
备注:if语句只能检测是否语句执行后的返回值是否为0
4、test命令
test命令提供一种检测if-then语句中不同条件的方法。
test可以评估一下3类条件
- 数值比较
-eq -ge -gt -le -lt -ne
== >= > <= < != 字符串比较
= != < >
-n str1 检查str1的长度是否大于0
-z str1 检查str1的长度是否为0
**备注:
1>大于和小于符号必须用转义字符,否则shell会将他们当成重定向符号,将字符串看作文件名;if [ $val1 \> $val2 ] then ... fi
2>大于和小于顺序与在sort命令中的顺序不同;
- 文件比较
格式:
Test conditon
配合if语句的两种形式
1)
if test condition
then
commands
fi
2)
if [ condition ]
then
commands
fi
备注:方括号前后必须加空格
5、复合条件检查
[ condition1 ] && [ condition2 ]
[ condition1 ] || [ condition2 ]
6、if-then的高级特征
- 双圆括号表示数学表达式
- 双方括号表示高级字符串处理函数
备注:双圆括号内的表达式不必转义大于号
val1=10
if (( $val1 ** 2 >90))
then
(( val2 = $val1 ** 2))
echo "The square of $val1 is $val2"
fi
双方括号提供了模式匹配
if [[ $USER == r* ]]
then
echo "Hello $USER"
else
echo "Sorry, I don't know you"
fi
7、case命令
case variable in
pattern1 | pattern2) commands1;;
pattern3) commands2;;
*) default commands;;
esac