一、双分支条件判断语句
前文中介绍过单分支条件判断语句,即一段脚本中只判断满足条件的情况,对不满足条件的情况,不做任何操作。但在实际开发中,对于条件不满足的情况,往往是需要对其加以控制的。对于这样既要判断满足条件,也要判断不满足条件的语句结构,称为双分支条件判断语句,其结构为:
if 条件; then
语句1
语句2
...
else
语句1
语句2
...
fi
二、双分支条件判断语句实例演示
例1. 沿用前文中判断用户是否存在的脚本,对其加以改进:如果指定的用户存,先说明其已经存在,并显示其ID号和SHELL;否则,就添加用户,并显示其ID号;
[root@localhost tutor]# vim if_user3.sh
#!/bin/bash # UserName=user1 if id $UserName &> /dev/null; then echo "$UserName exists." grep "^$UserName:" /etc/passwd |cut -d: -f3,7 else useradd $UserName grep "^$UserName:" /etc/passwd |cut -d: -f3 fi
[root@localhost tutor]# bash -n if_user3.sh
[root@localhost tutor]# chmod +x if_user3.sh
[root@localhost tutor]# ./if_user3.sh
user1 exists. 500:/bin/bash
[root@localhost tutor]# userdel -r user1
[root@localhost tutor]# ./if_user3.sh
500
[root@localhost tutor]# bash -x if_user3.sh
# 显示该脚本的执行过程 + UserName=user1 + id user1 + echo 'user1 exists.' user1 exists. + cut -d: -f3,7 + grep '^user1:' /etc/passwd 500:/bin/bash