admin 发表于 2017-12-18 22:07:44

1.8 if-then-else语句

   在if-then语句中,不管命令是否成功执行,你都只有一种选择。   if-then-else语句在语句中提供了另外一组命令。if command
then
commands
else
commands
fi举例:if grep 10.1.1.200 /etc/hosts
then echo "host1 found"
else echo "host1 is not found!"
fi上述代码首先是去调用grep命令,去/etc/hosts文件中搜索10.1.1.200这个字符串,如果找到就输出“host1 found!”,如果没找到,就输出“host1 is not found!”
    输出:# ./test
host1 is not found!
# ./test
10.1.1.200    controler
host1 found可以看到,本程序执行了两次。第一次因为没有搜索到,所以输出host1 is not found!。第二次是通过vim编辑器在/etc/hosts里增加了10.1.1.200 controller这一行,所以搜索找到了。
    再次执行程序,输出了找到的结果,并打印host1 found。
   
页: [1]
查看完整版本: 1.8 if-then-else语句