加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

shell 编程if条件判断与if 真假判断

发布时间:2020-12-15 16:20:39 所属栏目:安全 来源:网络整理
导读:if条件判断与if 真假判断 目录: 1.正确写法 2.错误写法 3.总结 一、正确写法 在编写shell脚本时,为简化代码的行号及结构的简约型,通常将命令执行结果和判断通过一条语句进行编写(在C语言编写程序时,经常遇到此种写法),如: [root@centos7 ~]#touch te

if条件判断与if真假判断


目录:

1.正确写法

2.错误写法

3.总结


一、正确写法

在编写shell脚本时,为简化代码的行号及结构的简约型,通常将命令执行结果和判断通过一条语句进行编写(在C语言编写程序时,经常遇到此种写法),如:

[root@centos7 ~]#touch test.sh

if useradd root &>/dev/null ; then #如果用户添加成功,则不显示,否则显示用户添加失败
echo "user1 created successfu" &>/dev/null

else
echo "user1 created failed"

fi
[root@centos7 ~]#chmod +x test.sh

[root@centos7 ~]#./test.sh

user1 created failed

二、错误写法

但是如果因记忆失误或编写脚本习惯性,添加[ ]判断时,脚本变为如下:

[root@centos7 ~]#touch test.sh

if [ useradd user1 &>/dev/null ] ; then #如果用户添加成功,则不显示,否则显示用户添加失败
echo "user1 created successfu" &>/dev/null

else
echo "user1 created failed"

fi
[root@centos7 ~]#chmod +x test.sh

[root@centos7 ~]#./test.sh #

user1 created failed

[root@centos7 ~]#id user1 #用户添加成功,本应该不显示,但显示添加失败
uid=1005(user1) gid=1005(user1) groups=1005(user1)

[root@centos7 ~]#userdel -r user1

######################调试模式执行###################################################

[root@centos7 ~]#bash -x 4.sh
+ '[' useradd user1 ']' #命令执行成功,但显示失败,原因在添加[ ]条件判断,

+ echo 'user1 created failed' #条件判断默认是判断useradd user1添加成功后,命令结果无显示
user1 created failed #因此默认[ -n '' ]为空,因此显示失败

三、总结

总结,在使用if判断及命令执行结果的语法结构时,命令行中间切忌加判断,条件判断必须加条件判断表达式。其本质是,if 真假判断 和 if 条件判断的区别

真假判断 条件判断

if cmd ; then if [ statement ]; then

cmd statement cmd statement

else else

cmd statement cmd statement

fi fi

####################################################################################

###具体详情请咨询微信:QQ767743577 邮箱地址: xuewei_bo@126.com,有问必答,有答必应,人人为我,我为人人###

####################################################################################

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读