admin 发表于 2017-12-18 22:27:26

1.9 嵌套的if-then语句

   有时你需要检查脚本代码中的多种条件。对此,可以使用嵌套的if-then语句。   嵌套的if-then语句位于主if-then-else语句的else代码块中。
    代码:if grep 10.1.1.100 /etc/hosts
then echo "controller found"
else
   if grep 10.1.1.101 /etc/hosts
   then echo "compute found"
   else echo "controller and compute are not found!"
   fi
fi执行之前,先来看看/etc/hosts文件里的内容,只有一行。# more /etc/hosts
10.1.1.101compute执行该代码,得到以下输出:# ./test
10.1.1.101compute
compute found符合预期,程序已经走到了嵌套的if-then-else里面。    另外,可以使用else部分的另一种形式: elif。这样就不用再书写多个if-then语句了。 elif使用另一个if-then语句延续else部分。if command1
then
commands
elif command2
then
more commands
fielif语句行提供了另一个要测试的命令,这类似于原始的if语句行。如果elif后面的命令成功执行,那么将执行then后面的命令。

页: [1]
查看完整版本: 1.9 嵌套的if-then语句