首页 > 其他 > 详细

流程控制语句

时间:2020-07-16 15:25:19      阅读:45      评论:0      收藏:0      [点我收藏+]

语法格式

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!