问题
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 theinfMsg "true"
statement. (&& -> If part one is true, run the second part).- Now we have
|| infMsg "false"
. If theinfMsg "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 theinfMsg "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