linux 三目运算符,Shell脚本:shell逻辑判断-三目运算符

?:;

等同于C语言中的if语句

if (表达式1)

表达式2;

else

表达式3;

而在bash shell 中也有类似的方式

echo $((2>1?2:1))

但是這里 $(()) 只能进行数值大小的判断

使用command进行三目运算应该这样使用

command1 && command2 || command3

在shell中,很多人理解为下面的if语句

if command1;then

command2

else

command3

fi

这是错误的,原因是没有深刻理解&& 和 ||

下面的命令很好的指出错误的原因

#date && echo "It's sunny today" || echo "the weather is terrible"

Thu Aug 20 11:09:35 EDT 2015

It's sunny today

#date && "It's sunny today" || echo "the weather is terrible"

Thu Aug 20 11:10:45 EDT 2015

-bash: It's sunny today: command not found

the weather is terrible

||会判断前一条命令的状态还回值,如果为false,就执行后面的语句

在这里 “It’s sunny today” 命令是错误的,于是后面 echo “the weather is terrible” 就执行了深入研究使用{}解决||判断问题

command1 && { command2 ;echo -n ;} || commadn3

如果command1正确 ||就只会接受来自echo -n的状态还回值,所以不会执行后面的command3

如果command1失败 &&直接跳过,||判断command1失败,执行command3

三目运算符的主要目的是达到简写的功能,避免不必要的简单if语句

在日常使用中 1 && 2 || 3 确实很实用

下面举几个列子

判断文件是否存在,如果存在就继续执行脚本,不存在就退出报错

使用if判断文件存在,然后else部分写exit。~~but,

if [ -e $path ];then

??

else

exit 1

fi

如果文件存在如何进行?

这个时候只能反向思路,不存在怎么样,但是这样就和判断逻辑相反

if [ ! -e $path ];then

exit 1

fi

但是这样就简便了很多

[ -e $path ] || exit 1

需要有顺序的连续执行多条命令,并且判断命令正确,如果命令错误就执行 “echo error”

在这里如果使用if就需要嵌套多层,十分麻烦,也浪费时间

if command1;then

if command2;then

if command3;then

command4

else

echo "error"

fi

else

echo "error"

fi

else

echo "error"

fi

而使用&&就简化了很多

commad1 && command2 && command3 && command4 || echo "error"

博主很喜欢使用三目运算符进行逻辑的判断

下面是举例

#在很多脚本中需要版判系统是否存在安装包或者命令

[ -e /usr/sbin/iptables ] || { echo "iptables-services not installed" && exit 1 ;}

#博主编写比较两个文件夹差异的脚本中,如果参数是两个存在的文件进行的判断

[ -f "$1" ] && [ -f "$2" ] && { cmp $1 $2 >/dev/null 2>&1 && echo 'The two files are the same' && exit 0|| { echo -ne $red 'The two files are not same'\n && exit 0 ;} ;}

c25fc120db12dd76a8265bee7572938b.pngShell脚本:shell逻辑判断-三目运算符

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值