在if-then语句中,不管命令是否成功执行,你都只有一种选择。如果命令返回一个非0退出状态码,则bash shell会继续执行脚本中的下一条命令。在这种情况下,如果能够执行另一组命令就好了。这正是if-then-else语句的作用。
if-then-else语句在语句中提供了另外一组命令:
if command
then
command
else
command
fi
当if语句中的命令返回退出状态码0时,then部分中的命令会被执行,这跟普通的if-then语句一样。当if语句中的命令返回非0退出状态码时,bash shell会执行else部分中的命令。
现在你可以复制并修改测试脚本,加入else部分:
$ cp test3.sh test4.sh
$
$ nano test4.sh
$
$ cat test4.sh
#!/bin/bash
# testing the else section
#
testuser=NoSuchUser
#
if grep $testuser /etc/passwd
then
echo "The scropt files in the home directory of $testuser are:"
ls /home/$testuser/*.sh
echo
else
echo "The user $testuser does not exist on this system."
echo
fi
echo "We are outside the if statement"
$
$ ./test4.sh
The user NoSuchUser does not exist on this system.
We are outside the if statement
这样就友好多了。跟then部分一样,else部分可以包含多条命令。fi语句说明else部分结束。