shell结构化命令——使用if-then语句

最基本的结构化命令是if-then语句。if-then语句的格式如下:

if command

then

      commands

fi

如果之前用过其他编程语言的if-then语句,那么这种形式可能会让你有点儿困惑。在其他编程语言中,if语句之后的对象是一个等式,其求值结果为TRUE或FALSE。但bash shell的if语句并非如此。

bash shell的if语句会执行if之后的命令。如果该命令的退出状态码为0(命令成功运行),那么位于then部分的命令就会被执行。如果该命令的退出状态码是其他值,则then部分的命令不会被执行,bash shell会接着处理脚本中的下一条命令。fi语句用来表示if-then语句到此结束。

下面用一个简单的例子来解释一下这个概念:

$ cat test1.sh
#!/bin/bash
# testing the if statement
if pwd
then
     echo "it worked"
fi

该脚本在if行中使用了pwd命令。如果命令成功结束,那么echo语句就会显示字符串。当你在命令行中运行该脚本时,会得到如下结果:

$ ./test1.sh
/home/christine/scripts
It worked

shell执行了if行中的pwd命令。由于退出状态码是0,因此它也执行了then部分的echo语句。来看另一个例子:

$ cat test2.sh
#!/bin/bash
# testing an incorrect command
if IamNotaCommand
then
     echo "It worked"
fi
echo "We are outside the if statement"
$
$ ./test2.sh
./test2.sh: line 3:IamNotaCommand:command not found
We are outside the if statement

在这个例子中,我们在if语句中故意使用了一个不存在的命令IamNotaCommand。由于这是个错误的命令,因此会产生一个非0的退出状态码,bash shell因此跳过了then部分的echo命令。还要注意,if语句中的那个错误命令所产生的错误消息依然会显示在脚本的输出中。有时你可能不想看到错误信息,后续会讲解如何避免这种情况。

注意:在有些脚本中,你可能看到过if-then语句的另一个形式:

           if command;then

              commands

           fi

           通过把分号(;)放在待求值的命令尾部,可以将then语句写在同一行,这样看起来更像其他编程语言中的if-then语句。

 能出现在then部分的命令可不止一条。你可以像脚本中其他地方一样在这里列出多条命令。bash shell 会将这些命令视为一个代码块,如果if语句行命令的退出状态值为0就,那么代码块中所有的命令都会被执行;否则,会跳过整个代码块:

$ cat test3.sh
#!/bin/bash
# testing multiple commands in the then block
#
testuser=christine
#
if grep $testuser /etc/passwd
then
    echo "This is my first command in the then block."
    echo "This is my second command in the then block."
    echo "I can even put in other command besides echo:"
    ls /home/$testuser/*.sh
fi
echo "We are outside the if statement"

if语句行使用grep命令在/etc/passwd文件中查找系统中是否存在某个特定用户。如果存在,则脚本会显示一些文本信息并列出该用户$HOME目录的bash脚本文件:

$ ./test3.sh
christine:x:1001:1001::/home/christine:/bin/bash
This is my first command in the then block.
This is my second command in the then block.
I can even put in other commands besides echo:
/home/christine/factorial.sh
We are outside the if statement

但是,如果将testuser变量设置成一个系统中不存在的用户,则不执行then代码块中的任何命令:

$ cat test3.sh
#!/bin/bash
# testing multiple commands in the then block
#
testuser=NoSuchUser
#
if grep $testuser /etc/passwd
then
    echo "This is my first command in the then block."
    echo "This is my second command in the then block."
    echo "I can even put in other command besides echo:"
    ls /home/$testuser/*.sh
fi
echo "We are outside the if statement"
$
$ ./test3.sh
We are outside the if statement

毫无惊喜可言。如果在这里显示一些消息说明系统中没有该用户,则会显得更友好。

  • 18
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值