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

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 邮箱地址: [email protected],有问必答,有答必应,人人为我,我为人人###

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

相关文章

用的openwrt路由器,家里宽带申请了动态公网ip,为了方便把2...
#!/bin/bashcommand1&command2&wait从Shell脚本并行...
1.先查出MAMP下面集成的PHP版本cd/Applications/MAMP/bin/ph...
1、先输入locale-a,查看一下现在已安装的语言2、若不存在如...
BashPerlTclsyntaxdiff1.进制数表示Languagebinaryoctalhexa...
正常安装了k8s后,使用kubect工具后接的命令不能直接tab补全...