参考书目:《Linux命令行与shell脚本编程大全》
文章内容如下:
在shell语言中,最基本的结构化命令是 if-then 语句。if-then 语句基本格式如下:
if command
then
commands
fi
bash shell 的 if 语句会运行 if 之后的命令。如果该命令的退出状态码为0(命令成功运行),那么位于 then 部分的命令就会被执行。如果该命令的退出状态码是其他值,则 then 部分命令不会被执行,bash shell 会接着处理脚本中的下一条命令。fi 语句用来表示 if-then 语句到此为止。
关于退出状态码
对于成功结束的命令,其退出状态码是 0。对于因错误而结束的命令,其退出状态码是一个0~255的正整数。
例:
#!/bin/bash
if pwd
then
echo "it worked."
fi
该脚本在 if 行中使用了 pwd 命令。如果命令成功结束,那么 echo 语句就会显示字符串。在命令行中运行脚本,得到如下结果:
wsy@localhost:~/Shell$ ./test1.sh
/home/wsy/Shell
it worked.
shell 执行了 if 行中的 pwd 命令。由于退出状态码是0,因此它也执行了 then 部分的 echo 语句。
再来查看一个退出状态码非0的例子:
#!/bin/bash
if IamNotaCommand
then
echo "it worked."
fi
echo "We are outside the if statement"
本例中,我们在 if 语句中故意使用了一个不存在的命令 IamNotaCommand
。由于这是个错误的命令,因此会产生一个非0的退出状态码,bash shell 因此跳过了 then 部分的 echo 命令,但要注意的是,if 语句中的那个错误命令执行所产生的消息依然会显示在脚本的输出中。
执行结果如下:
wsy@localhost:~/Shell$ ./test2.sh
./test2.sh:行3: IamNotaCommand: 未找到命令
We are outside the if statement
注意:
if-then 语句还有另一种形式,在有些脚本中也会经常遇到:
if command; then
commands
fi
能出现在 then 部分的命令可不止一条,bash shell 会将列在 then 部分的所有命令视为一个代码块,如果 if 语句行命令的退出状态码为 0,那么代码块中的所有命令都会被执行;否则会跳过整个代码块:
#!/bin/bash
testuser=wsy
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 commands besides echo:"
ls /home/$testuser
fi
echo "We are outside the if statement"
if 语句行使用grep命令在 /etc/passwd 文件中查找系统中是否存在某个特定用户,如果存在,则脚本会显示一些文本信息并列出该用户 $HOME 目录中的文件:
wsy@localhost:~/Shell$ ./test3.sh
wsy:x:1000:1000:wsy:/home/wsy:/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:
anaconda3 Shell Win_Shared WSY 公共 模板 视频 图片 文档 下载 音乐 桌面
We are outside the if statement
但是,如果将 testuser 变量设置成一个系统中不存在的用户,则不会执行 then 代码块中的任何命令:
wsy@localhost:~/Shell$ cat test3.sh
#!/bin/bash
testuser=www
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 commands besides echo:"
ls /home/$testuser
fi
echo "We are outside the if statement"
wsy@localhost:~/Shell$ ./test3.sh
We are outside the if statement
在 if-then 语句中,不管命令是否执行成功,都只有一种选择。如果命令返回一个非0退出状态码,则bash shell 会继续执行脚本中的下一条命令。在这种情况下,如果能够执行另一组命令就好了,这正是 if-then-else 语句的作用,格式如下:
if command
then
commands
else
commands
fi
当 if 语句中的命令退出状态码为0时,then 部分的命令会被执行,这跟普通的 if-then 语句一样。当 if 语句中的命令返回非0退出状态码时,bash shell 会执行 else 部分中的命令。
例:
#!/bin/bash
testuser=NoSuchUser
if grep $testuser /etc/passwd
then
echo "The files in the hone directory of $testuser are:"
ls /home/$testuser
echo
else
echo "The user $testuser does not exist on this system."
echo
fi
echo "We are outside the if statement."
执行如下:
wsy@localhost:~/Shell$ ./test4.sh
The user NoSuchUser does not exist on this system.
We are outside the if statement.
未完待续。。。