ternary construction not equivalent with if then else

大憨熊 提交于 2020-01-30 08:48:05

问题


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"

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

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.

Am I right?


回答1:


This command:

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

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

If you use this command:

test 1 && date || echo "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"

will not print anything




回答2:


What you refer to as the ternary version is actually equivalent to:

if (test 1); then
  if ! ls /undef_dummy > /dev/null 2>&1; then
    echo "else stmt"
  fi
fi

and is pretty different from saying:

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


来源:https://stackoverflow.com/questions/19857792/ternary-construction-not-equivalent-with-if-then-else

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!