Search code examples
bashif-statementexit-code

Catch bash exit code in if statement


If I do a simple test of exit codes directly with single commands:

[user@localhost ~]$ date
Tue Sep  8 14:00:11 CEST 2020
[user@localhost ~]$ echo $?
0
[user@localhost ~]$ dat
bash: dat: command not found...
[user@localhost ~]$ echo $?
127

But if I want to get them into an if sentence, I see that for the exit code 0 the output is OK, however, for the "command not found" code (it should be 127) it returns "1".

[user@localhost ~]$ date 
Tue Sep  8 14:02:18 CEST 2020
[user@localhost ~]$ if [ $? -eq 0 ]; then   echo "Success: $?"; else   echo "Failure: $?" >&2; fi
Success: 0
[user@localhost ~]$ dat
bash: dat: command not found...
[user@localhost ~]$ if [ $? -eq 0 ]; then   echo "Success: $?"; else   echo "Failure: $?" >&2; fi
Failure: 1

What am I missing?


Solution

  • Every command has it own exit state, so the command [ 1 will override $?. To prevent this, save the exit code to a variable, and use that in the if statement;

    le=$?
    if [ "$le" -eq 0 ]; then   echo "Success: $le"; else   echo "Failure: $le" >&2; fi
    

    Try it online!


    1: The single bracket [ is actually an alias for the test command, it's not syntax. For more info, check this comment on unix.stackexchange