1、if条件分支语句
if expr1(条件测试) #如果expr1为真,返回0
then
commands1
elif expr2
then
commands2
.... ...
else
commands
fi #if语句必须以fi终止
下面看一个实例:
1 #! /bin/bash 2 3 if [ $# -ne 1 ] 或 if [ $# -ne 1];then 4 then 5 echo "Usage: $0 username " 6 exit 1 7 fi 8 9 echo $1
elif可以有多个,else最多有1个。if语句必须以fi结束;commands为可执行语句块,如果为空,需使用shell提供的空命令“:”,即冒号。改命令不做任何事,只返回推出状态0
2、case选择分支语句
case expr in #expr为表达式,关键词in不要忘
pattern1) #若expr与pattern1匹配,注意括号
commands1 #执行
;; #跳出case结构
pattern2)
commands2
;;
... ...
*) #若expr与上面所有pattern都不匹配
commands
;;
esac #必须以esac终止
1 #! /bin/bash 2 3 case $1 in 4 A) 5 echo this is A 6 ;; 7 B|b) 8 echo this is B or b 9 ;; 10 *) 11 echo others 12 ;; 13 esac