Shell脚本语法-- if/then/elif/else/fi  

和C语言类似,在Shell中用if、then、elif、else、fi这几条命令实现分支控制。这种流程控制语句本质上也是由若干条Shell命

 
令组成的,例如先前讲过的
 
 
  
  1. if [ -f ~/.bashrc ]; then 
  2.     . ~/.bashrc 
  3. fi 
其实是三条命令,if [ -f ~/.bashrc ]是第一条,then . ~/.bashrc是第二条,fi是第三条。如果两条命令写在同一行则需要用;
 
号隔开,一行只写一条命令就不需要写;号了,另外,then后面有换行,但这条命令没写完,Shell会自动续行,把下一行接在then
 
后面当作一条命令处理。和[命令一样,要注意命令和各参数之间必须用空格隔开。if命令的参数组成一条子命令,如果该子命令
 
的Exit Status为0(表示真),则执行then后面的子命令,如果Exit Status非0(表示假),则执行elif、else或者fi后面的子命
 
令。if后面的子命令通常是测试命令,但也可以是其它命令。Shell脚本没有{}括号,所以用fi表示if语句块的结束。见下例:
 
 
  
  1. #! /bin/sh 
  2.  
  3. if [ -f /bin/bash ] 
  4. then echo "/bin/bash is a file" 
  5. else echo "/bin/bash is NOT a file" 
  6. fi 
 
 
 
  
  1. if :; then echo "always true"; fi 
:是一个特殊的命令,称为空命令,该命令不做任何事,但Exit Status总是真。此外,也可以执行/bin/true或/bin/false得到真
 
或假的Exit Status。再看一个例子:
 
 
  
  1. #! /bin/sh 
  2.  
  3. echo "Is it morning? Please answer yes or no." 
  4. read YES_OR_NO 
  5. if [ "$YES_OR_NO" = "yes" ]; then 
  6.   echo "Good morning!" 
  7. elif [ "$YES_OR_NO" = "no" ]; then 
  8.   echo "Good afternoon!" 
  9. else 
  10.   echo "Sorry, $YES_OR_NO not recognized. Enter yes or no." 
  11.   exit 1 
  12. fi 
  13. exit 0 
上例中的read命令的作用是等待用户输入一行字符串,将该字符串存到一个Shell变量中。
此外,Shell还提供了&&和||语法,和C语言类似,具有Short-circuit特性,很多Shell脚本喜欢写成这样:
test "$(whoami)" != 'root' && (echo you are using a non-privileged account; exit 1)
&&相当于“if...then...”,而||相当于“if not...then...”。&&和||用于连接两个命令,而上面讲的-a和-o仅用于在测试表达
 
式中连接两个测试条件,要注意它们的区别,例如,
test "$VAR" -gt 1 -a "$VAR" -lt 3
和以下写法是等价的
test "$VAR" -gt 1 && test "$VAR" -lt 3
 
 
 
  
  1. #!/bin/bash 
  2. echo "Enter your name: "  
  3. read A 
  4. if [ "$A" = "GS" ];then 
  5.         echo "yes" 
  6. elif [ "$A" = "UC" ];then 
  7.         echo "no" 
  8. else 
  9.         echo  "your are wrong" 
  10. fi 
(注意:if、elif后要有空格,[]前后有空格,=前后有空格)
 
 
  
  1. #!/bin/bash 
  2. read -p  "Enter your name: " A 
  3. if [ "$A" = "GS" ];then 
  4.         echo "yes" 
  5. elif [ "$A" = "UC" ];then 
  6.         echo "no" 
  7. else 
  8.         echo  "your are wrong" 
  9. fi