I recently came across a code fragment in a shell script, which looked something like below
a=23
echo $a || exit $?
I think the intent is to exit the script if the command on the left hand (echo $a
in this example) fails. It also seems to be working that way.
However, I am having trouble trying to explain this. The way I reasoned about it is:
If left hand side command returns non zero then the entire expression evaluates to true and right hand side doesn't need to be evaluated. Left hand side would be evaluated to the return status of the command which would be non zero if the command failed and zero if the command succeeds. By this logic, right hand side (exit $?
) would be executed whenever the command is successful and short-circuited(not executed) whenever the command is unsuccessful. But the actual behavior on executing the script is the opposite.
How is this working? What does the left side evaluate to?