最基本的结构化命令就是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语句行故意放了一个不能工作的命