2

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?

Ajay Yadav
  • 798
  • 1
  • 8
  • 18
  • *non zero then the entire expression evaluates to true and right hand side doesn't need to be evaluated* -- this has UNIX exit status exactly backwards. 0 is the only value that is considered successful, thus true. – Charles Duffy Feb 07 '18 at 18:27
  • 1
    BTW, `$?` is the default exit status, so you could write `echo $a || exit` with the exact same effect. – Charles Duffy Feb 07 '18 at 18:30
  • Also: https://stackoverflow.com/questions/47196270/what-is-the-idea-in-this-bash-statement-command-true – Benjamin W. Feb 07 '18 at 18:31

1 Answers1

3

Exit statuses are not boolean values in the usual sense. 0 represents success, nonzero represents failure. || runs the RHS when the LHS succeeds (i.e., when it has an exit status of 0).

chepner
  • 497,756
  • 71
  • 530
  • 681