What is the correct way to use the bash if else && || shortcut?

守給你的承諾、 提交于 2021-02-08 09:56:53

问题


I have come across some strange behavious (well probably not strange but I don't understand it !)

I want to write some if / e,se statements using the bash shorthand syntax:

[[ 1 -eq 1 ]] && echo "true" || echo "false"

The output of the above code gives:

true

Now the code above actually works fine. But this next code does not:

[[ 1 -eq 1 ]] && infMsg "true" || infMsg "false"

infMsg is just a function. The output from the above code gives:

true
false

I only want it to say 'true'.

Is there something I am missing in the way the && || syntax handles exit codes from functions ?


回答1:


I suspect your exit code for 'infMsg' is not 0 (success). If we break down the first piece of code:

[[ 1 -eq 1 ]] && echo "true" || echo "false"

What's happening is:

  • The [[ 1 -eq 1 ]] && echo "true" portion of code is evaluated first since && has a higher precedence than || (more info[here1)
  • The first half of that returns true. Then, since the first half was true, the second half executes the echo "true" statement. (&& -> If part one is true, run the second part)
  • Now we have the || echo "false". This part actually doesn't get executed since the first half (echo "true") returned true since the echo printed successfully ((||-> If part one is false, run the second part).).

Now if we break down the second piece of code:

[[ 1 -eq 1 ]] && infMsg "true" || infMsg "false"

What's most likely happening is:

  • [[ 1 -eq 1 ]] && infMsg "true" is evaluated. The first side is true. Then, since the first half was true, the second half executes the infMsg "true" statement. (&& -> If part one is true, run the second part).
  • Now we have || infMsg "false". If the infMsg "true" from the previous command didn't return a status code that is interpreted as success (0), the first half is interpreted as false, triggering the infMsg "false"((||-> If part one is false, run the second part).)..

The important info to pull away here:

  • || only runs the second half if the first half is FALSE.
  • && only run the second half if the first half is TRUE.


来源:https://stackoverflow.com/questions/15538782/what-is-the-correct-way-to-use-the-bash-if-else-shortcut

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