条件语句
-
if
if condition;then statement fi
-
if else
if condition;then statement else statement fi
-
if elif else
if condition;then statement elif condition2;then statement else statement fi
shell的if语句还提供了逻辑运算符将多个状态组合起来
&&
:与||
:或!
:非
选择语句
case:
case expr in
pattern1)
逻辑1
;;
pattern2 | pattern3)
逻辑2
;;
[abc])
逻辑3
;;
[0-9])
逻辑4
;;
*)
逻辑
easc
*
:表示任意字符串
[abc]
:表示a,b,c中任意一个
[0-9]
:表示0-9中任意一个数字
|
:表示多个匹配规则组合
select:是shell独有的,这个做交互式的脚本时候有用。
循环语句
for循环
C风格的for循环
for((exp1;exp2;exp3))
do
statement
done
Python风格的for循环
for var in value_list
do
statements
done
value_list:
- 直接给出具体的值,使用空格分隔
- 给出一个值范围
{start..end}
,使用两个点连接 - 使用命令的执行结果`` 或者$() 获取命令执行结果
- 使用特殊变量$#、$*、$@等
while循环
注意,在 while 循环体中必须有相应的语句使得 condition 越来越趋近于“不成立”,只有这样才能最终退出循环,否则 while 就成了死循环,会一直执行下去,永无休止。
while condition
do
statements
done
...