1

I need to understand this command:

[ $? == 1 ] && return 0
5

The expression $? evaluates to the exit code of the previous command.

&& is a command separator which will run the second command if and only if the first command returns an exit code of zero.

[ or test is a shell tool to make various comparative tests.

I should point out that == is the wrong test to use here as that is for string comparison; -eq is the equality test for numerical comparison.

So: [ $? -eq 1 ] && return 0 will look at the exit code of the immediately previous command, and compare it to 1. If there is a match, the command return 0 will be executed (thereby bypassing what I presume to be subsequent commands in the function wherein this test lies).

The distinction between the usage of == and -eq is that [ 01 -eq 1 ] is true whilst [ 01 == 1 ] is false.

  • Good answer, covers everything. May also wanna mention return is used in functions, so OP's command probably belongs in a function somewhere – Sergiy Kolodyazhnyy May 21 '18 at 20:36
  • 1
    One step ahead of you (: – DopeGhoti May 21 '18 at 20:37
  • The difference between = and -eq probably doesn't matter here, since $? wouldn't usually contain leading zeroes. However, == is nonstandard, the standard operator is =. – ilkkachu May 21 '18 at 20:39
  • test's manual page indicates that == is synonymous with = for compatibility with other implementations. Either way, the point is that -eq is the right tool for this comparison. – DopeGhoti May 21 '18 at 20:43
  • 1
    A better test, assuming one wants to test of any error and not a specific error code, would have been [ "$?" -ne 0 ]. The $? should be quoted. Also, its usually better to just use utility || exit or if ! utility; then exit; fi. – Kusalananda May 22 '18 at 5:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.