360

I was wondering what would be the best way to check the exit status in an if statement in order to echo a specific output.

I'm thinking of it being

if [ $? -eq 1 ]
then
   echo "blah blah blah"
fi

The issue I am also having is that the exit statement is before the if statement simply because it has to have that exit code. Also, I know I'm doing something wrong since the exit would obviously exit the program.

codeforester
  • 28,846
  • 11
  • 78
  • 104
deadcell4
  • 3,815
  • 3
  • 10
  • 10
  • 3
    Plaese post your complete script (or at least a broader scope). Else this seems fine. – RedX Oct 31 '14 at 13:21
  • 7
    If you need to use the exit code from some particular program invocation in two different places, then you need to preserve it - something along the lines of `some_program; rc=$?; if [ ${rc} -eq 1 ] .... fi ; exit ${rc}` – twalberg Oct 31 '14 at 14:37

8 Answers8

358

Every command that runs has an exit status.

That check is looking at the exit status of the command that finished most recently before that line runs.

If you want your script to exit when that test returns true (the previous command failed) then you put exit 1 (or whatever) inside that if block after the echo.

That being said if you are running the command and wanting to test its output using the following is often more straight-forward.

if some_command; then
    echo command returned true
else
    echo command returned some error
fi

Or to turn that around use ! for negation

if ! some_command; then
    echo command returned some error
else
    echo command returned true
fi

Note though that neither of those cares what the error code is. If you know you only care about a specific error code then you need to check $? manually.

Etan Reisner
  • 68,917
  • 7
  • 78
  • 118
  • 20
    @deadcell4 When one needs to terminate a shell script on a program failure, the following idiom is useful `a_command || return 1` – gboffi Oct 31 '14 at 13:32
  • 15
    @gboffi `return` only works in a function and a sourced script. You need `exit` for the other case (which does too much in a function and a sourced script). But yes, that's certainly a reasonable pattern if you don't need any specific cleanup or extra output. – Etan Reisner Oct 31 '14 at 13:33
  • 1
    I have to say that `dash`, the default non-interactive shell in many modern linux distributions, don't care of the distinction between `return` and `exit` inside of executed shell scripts. `dash` exits the script even if I use `return` in it. – gboffi Oct 31 '14 at 14:32
  • 1
    What is the logic behind the last two checks? It seems counter-intuitive that the condition `if ` passes if the exit code is 0. In any other language it would be the other way around – sjw Jun 04 '19 at 11:01
  • 4
    IMPORTANT NOTE: This won't work for pipes. `if ! some_command | some_other_command` will ignore the status of some_command. The two most command workarounds are to `set -o pipefail` (may change functionality in other parts of your program) or to move the `if` statement to `if [[ ${PIPESTATUS[0]} -ne 0 ]]` as a separate follow-up command (ugly, but functional). If you're using `set -e` then you'll also want to add `|| true` to the end of the pipe when using the second solution since removing the pipe from the control flow offered by `if` would otherwise cause it to immediately exit. – Alex Jansen Jul 04 '19 at 02:06
  • What about `grep`; which has 3 possible exit codes: 0 - something was selected, 1 - nothing; 2 - an error. – manu Jan 07 '21 at 06:15
  • Is there a way to fetch the error code in the "then" branch above, I know it returned non-zero but can I get exactly what flavor of non-zero? – chrisinmtown Feb 10 '21 at 21:57
251

Note that exit codes != 0 are used to report error. So, it's better to do:

retVal=$?
if [ $retVal -ne 0 ]; then
    echo "Error"
fi
exit $retVal

instead of

# will fail for error codes > 1
retVal=$?
if [ $retVal -eq 1 ]; then
    echo "Error"
fi
exit $retVal
anr78
  • 1,198
  • 2
  • 14
  • 26
Oo.oO
  • 9,723
  • 3
  • 19
  • 40
  • You must test on retVal, because $? after the assignment of retVal is not the return value from your command. – anr78 Apr 19 '18 at 08:05
  • Not really: http://mywiki.wooledge.org/BashFAQ/002 - however, I agree that edit improves the readability. – Oo.oO Apr 19 '18 at 08:32
  • 1
    Just found this post that explains it https://stackoverflow.com/questions/20157938/bash-exit-code-of-variable-assignment-to-command-substitution – anr78 Apr 19 '18 at 08:58
  • [`dnf check-update`](https://dnf.readthedocs.io/en/latest/command_ref.html#check-update-command-label) returns 0 (no updates), 100 (updates available) or 1 (error). – jww Jun 17 '19 at 22:37
  • 1
    @jww - well, that's not quite a good idea to go against convention (https://www.gnu.org/software/bash/manual/html_node/Exit-Status.html). But, well, there is nothing to prevent that. If `dnf` developers have chosen this way, it's their choice. But still, their choice doesn't make the specification to be broken :) – Oo.oO Jun 18 '19 at 10:04
58

Alternative to explicit if statement

Minimally:

test $? -eq 0 || echo "something bad happened"

Complete:

EXITCODE=$?
test $EXITCODE -eq 0 && echo "something good happened" || echo "something bad happened"; 
exit $EXITCODE
Elias Dorneles
  • 19,202
  • 9
  • 63
  • 95
Catskul
  • 15,635
  • 13
  • 75
  • 111
52

$? is a parameter like any other. You can save its value to use before ultimately calling exit.

exit_status=$?
if [ $exit_status -eq 1 ]; then
    echo "blah blah blah"
fi
exit $exit_status
chepner
  • 389,128
  • 51
  • 403
  • 529
23

Just to add to the helpful and detailed answer:

If you have to check the exit code explicitly, it is better to use the arithmetic operator, (( ... )), this way:

run_some_command
(($? != 0)) && { printf '%s\n' "Command exited with non-zero"; exit 1; }

Or, use a case statement:

run_some_command; ec=$?  # grab the exit code into a variable so that it can
                         # be reused later, without the fear of being overwritten
case $ec in
    0) ;;
    1) printf '%s\n' "Command exited with non-zero"; exit 1;;
    *) do_something_else;;
esac

Related answer about error handling in Bash:

codeforester
  • 28,846
  • 11
  • 78
  • 104
19

For the record, if the script is run with set -e (or #!/bin/bash -e) and you therefore cannot check $? directly (since the script would terminate on any return code other than zero), but want to handle a specific code, @gboffis comment is great:

/some/command || error_code=$?
if [ "${error_code}" -eq 2 ]; then
   ...
Sled
  • 16,514
  • 22
  • 110
  • 148
dtk
  • 1,144
  • 2
  • 16
  • 17
  • Doesn't this break if `/some/command` is in the PATH? `error_code` is not set. – Justin Apr 09 '21 at 06:34
  • I don't see how that would interfere. You can try `/bin/mkdir` on an existing directory, that should return 1. Are you certain the command you tried did return an exit code other than 0? `/usr/bin/file` on an non-existant file for example prints an error but still returns 0 – dtk Apr 09 '21 at 07:41
5

If you are writing a function, which is always preferred, you should propagate the error like this:

function() {
    if some_command; then
        echo worked
    else
        return $?
fi
}

This will propagate the error to the caller, so that he can do things like function && next as expected.

Nishant
  • 17,152
  • 14
  • 56
  • 80
3

Using zsh you can simply use:

if [[ $(false)? -eq 1 ]]; then echo "yes" ;fi

When using bash & set -e is on you can use:

false || exit_code=$?
if [[ ${exit_code} -ne 0 ]]; then echo ${exit_code}; fi