流程控制语句 if
1、单分支分支if语句
语法格式:
if 条件 then commands fi
if语句流程图:
注:根据我们的命令退出码来进行判断(echo $? =0),如果是0,那么就会执行then后面的命令
例1:
[root@xuegod63 ~]# vim if-1.sh
#!/bin/bash if ls /mnt then echo "it's ok" fi
[root@xuegod63 ~]# bash !$
bash if-1.sh
CentOS_BuildTag GPL LiveOS RPM-GPG-KEY-CentOS-7
EFI images Packages RPM-GPG-KEY-CentOS-Testing-7
EULA isolinux repodata TRANS.TBL
it's ok
双分支if语句
语法格式:
if command ; then commands else commands fi
例2:
[root@xuegod63 ~]# cat if-2.sh
#!/bin/bash if grep root /etc/passwd ; then echo "it's ok" else "it's err" fi
[root@xuegod63 ~]# sh if-2.sh
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
it's ok
例3:
[root@xuegod63 ~]# cat if-3.sh
#!/bin/bash if grep xuegod /etc/passwd ;then echo "it's ok" else echo "it's err" fi
[root@xuegod63 ~]# sh if-3.sh
it's err
多分支if语句
语法结构:
if 条件测试操作1 ; then commands elif 条件测试操作2 ; then commands elif 条件测试操作3 ; then commands ....... else commands fi
例4:判断用户在系统中是否存在,是否有家目录
[root@xuegod63 ~]# cat if-4.sh
#!/bin/bash read -p "input a user:" tu if grep $tu /etc/passwd ; then echo "the user $tu exists on this system" elif ls -d /home/$tu ; then echo "the user $tu not exists on this system" echo "$tu has a home directory" else echo "the user $tu not exists on this system" echo "$tu not has a direcotry" fi
[root@xuegod63 ~]# sh if-4.sh
Input a user: hr
chrony:x:994:990::/var/lib/chrony:/sbin/nologin
hr:x:1000:1000:hr:/home/hr:/bin/bash
the user hr exists on this system
[root@xuegod63 ~]# sh if-4.sh
Input a user: xuegod
/home/xuegod
xuegod has a directory