语法格式
if 条件
then
命令
fi
注意:if是根据命令退出码来判断(echo $?=0),如果是0,则表示为真,执行后面的命令
举例
[root@tzPC ~]# cat if-1.sh #!/bin/bash if ls /mnt then echo "ok!" fi
双分支if语句
语法格式
if 条件 ; then 命令 else 命令 fi
举例
[root@tzPC ~]# cat if-2.sh #!/bin/bash if grep root /etc/passwd ; then echo "ok!" else echo "no!" fi
多分支if语句
语法结构
if 条件1;then 命令 elif 条件2;then 命令 elif 条件3;then 命令 ... else 命令 fi
举例
查看tz用户是否存在
[root@tzPC ~]# ls -d /home/tz /home/tz [root@tzPC ~]# echo $? 0
脚本
[root@tzPC ~]# cat if-3.sh #!/bin/bash read -p "input a username:" name if grep $name /etc/passwd ;then echo "the user $name exists on this system!" elif ls -d /home/$name;then echo "the user $name not exists on this system!" echo "$name has a home directory" else echo "the user $name not exists on this system" echo "$name not has a direcotry" fi
原文:https://www.cnblogs.com/tz90/p/13322345.html