最基本的结构化命令就是if-then语句。if-then语句有如下格式。
if command
then
commands
fi
简单的例子:
$ cat test1.sh #!/bin/bash # testing the if statement if pwd then echo "It worked" fi $ |
---|
这个脚本在if行采用了pwd命令。如果命令成功结束,echo语句就会显示该文本字符串。在
命令行运行该脚本时,会得到如下结果
$ ./test1.sh /home/Christine It worked $ |
---|
shell执行了if行中的pwd命令。由于退出状态码是0,它就又执行了then部分的echo语句。
下面是另外一个例子
$ cat test2.sh #!/bin/bash # testing a bad 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语句行故意放了一个不能工作的命令。由于这是个错误的命令,所
以它会产生一个非零的退出状态码,且bash shell会跳过then部分的echo语句。还要注意,运行
if语句中的那个错误命令所生成的错误消息依然会显示在脚本的输出中
你可能在有些脚本中看到过if-then语句的另一种形式:
if command; then
commands
fi
通过把分号放在待求值的命令尾部,就可以将then语句放在同一行上了,这样看起来更
像其他编程语言中的if-then语句。
在then部分,你可以使用不止一条命令。可以像在脚本中的其他地方一样在这里列出多条
命令。bash shell会将这些命令当成一个块,如果if语句行的命令的退出状态值为0,所有的命令都会被执行;如果if语句行的命令的退出状态不为0,所有的命令都会被跳过。
$ cat test3.sh #!/bin/bash # testing multiple commands in the then section # testuser=Christine # if grep $testuser /etc/passwd then echo "This is my first command" echo "This is my second command" echo "I can even put in other commands besides echo:" ls -a /home/$testuser/.b* fi |
---|
if语句行使用grep命令在/etc/passwd文件中查找某个用户名当前是否在系统上使用。如果有
用户使用了那个登录名,脚本会显示一些文本信息并列出该用户HOME目录的bash文件
$ ./test3.sh Christine:x:501:501:Christine B:/home/Christine:/bin/bash This is my first command This is my second command I can even put in other commands besides echo: /home/Christine/.bash_history /home/Christine/.bash_profile /home/Christine/.bash_logout /home/Christine/.bashrc |
---|
但是,如果将testuser变量设置成一个系统上不存在的用户,则什么都不会显示。
if-then-else语句在语句中提供了另外一组命令。
if command
then
commands
else
commands
fi
当if语句中的命令返回退出状态码0时,then部分中的命令会被执行,这跟普通的if-then
语句一样。当if语句中的命令返回非零退出状态码时,bash shell会执行else部分中的命令。