if-then-else语句
在if-then语句中,不管命令是否成功执行,你都只有一种选择。如果命令返回一个非零的状态退出码,bash shell会继续执行脚本中的下一条命令。而if-then-else语句则可以提供另一组命令。
格式:
if command
then
commands
else
commands
fi
当if语句中的命令返回退出状态码0时,then部分中的命令会被执行,这跟普通的if-then语句一样。当if语句中的命令返回非零退出状态码时,bash shell会执行else部分的命令。
例:
[root@CHENDAJIE if-then-else-test]# cat test1
#!/bin/bash
# Testing the else section
#
testuser=NoSuchUser
#
if grep $testuser /etc/passwd
then
echo "The bash files for user $testuser are:"
ls -a /home/$testuser/.b*
echo
else
echo "The user $testuser does not exit on this system."
echo
fi
[root@CHENDAJIE if-then-else-test]# chmod u+x test1
[root@CHENDAJIE if-then-else-test]# ./test1
The user NoSuchUser does not exit on this system.