流程控制語句
阿新 • • 發佈:2020-07-16
語法格式
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