1. if-then
if command
then
commands
fi
2. if-then-else
if command
then
commands
else
commands
fi
3.嵌套if
if command1
the
commands
elif command2
then
commands
fi
4. test命令
如果test命令中列出的条件评估值为ture,test命令以0退出
test conditon
常用的形式:
if test condition
then
commands
fi
也可用下面形式替代:
if [ condition ]
then
commands
fi
注意: if后面的中括号与 condition 之间的空格必须存在
5. 数值比较
n1 -eg n2 检查n1是否等于n2; n1 -le n2 检查n1是否小于或等于n2
n1 -ge n2 检查n1是否大于或等于n2; n1 -lt n2 检查n1是否小于n2
n1 -gt n2 检查n1是否大于n2; n1 -ne n2 检查n1是否不等于n2
6.字符串比较
str1 = str2; str1 > str2; str1 != str2; str1 < str2;
-n str1 检查str1的长度是否大于0; -z str1 检查str1的长度是否为0
7. 文件比较
-d file 检查file是否存在并且是一个目录; -e file 检查file是否存在
-f file 检查file是否存在并且是一个文件; -r file 检查file是否存在并且可读
-s file 检查file是否存在并且部位空; -w file 检查file是否存在并且可写
-x file 检查file是否存在并且可执行; -O file 检查file是否存在并且被当前用户拥有
8. 复合条件检查
if-then语句使用布尔逻辑合并检查条件:
[ condition1 ] && [ condition ] ; [ condition ] || [ condition ]
9. if-then高级特性
双圆括号命令允许在比较中包含高级数学表达式 (( expression ))
val++; val--; ++val; --val; ! (逻辑非); ~ (逐位取反); ** (取幂 val ** 3);
&&(逻辑与); || (逻辑或);
双放括号命令为字符串比较提供高级功能 [[ expression ]]
可以使用test命令中使用的标准字符串比较, 还提供模式匹配功能:
匹配正则表达式 : if [[ $USER == *r ]]
10. case
case variable in
pattern1 | pattern2) commands1;;
pattern3) commands2;;
*) default commands;;
esac
11. for
设置字段分隔符 IFS=$'\n'; IFS=$':' (默认为空格)
for var in list
do
commands
done
c式的for:
for (( a=1; a<10; a++ ))
12. while
while test command
do
other commands
done
同样 test command 可以用 [ condition ] 替代.
13. until
until test commands
do
other commands
done
14. break continue
break 跳出内循环 break n 跳出外循环(n表示第几层外循环)
continue continue n