三元构造与if else else不相等 [英] ternary construction not equivalent with if then else

查看:55
本文介绍了三元构造与if else else不相等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下if/then测试(以bash格式):

The following if/then test (in bash):

if [ 1 ]; then ls /undef_dummy > /dev/null 2>&1; else echo "else stmt"; fi

似乎不等同于其三元版本:

seems not equivalent to its ternary version:

(test 1) && ls /undef_dummy > /dev/null 2>&1 || echo "else stmt"

第一个将不打印任何内容,但是第二个将打印"else stmt".

The first one will print nothing but the second one will print "else stmt".

这是因为||三元版本的运算符与测试(如果测试通过)所执行的命令的返回状态有关.但是通常,我们想要else语句仅与测试有关,因此在此处使用三元版本并不安全.

This is because the || operator in the ternary version relates to the return status of either the test or the command executed if the test passes. But usually, we want the else statement to only relate to the test, so it's not safe to use the ternary version here.

我是对的吗?

推荐答案

此命令:

(test 1) && ls /undef_dummy > /dev/null 2>&1 || echo "else stmt"

正在评估

|| ,因为 ls 将非零返回码返回给shell

|| is being evaluated because ls is returning non-zero return code to shell

如果使用此命令:

test 1 && date || echo "else stmt"

然后它将打印日期值,而不是 else stmt

Then it will print date value instead of else stmt

对命令进行适当的分组:

With proper grouping your command:

test 1 && { ls /undef_dummy > /dev/null 2>&1 || true; } || echo "else stmt"

将不会打印任何内容

这篇关于三元构造与if else else不相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆