9

How can one extract the exit code of a command and use it in a condition? For example look at the following script:

i=4
if [[ $i -eq 4 && $(command) -eq 0 ]]
    then
            echo "OK"
    else
            echo "KO"
    fi

If both the conditions are satisfied the script should do something. In the second condition, I need the check on the exit status (and not the command output as is the case in the script given above), to know if the command was successful or not.

Curious
  • 175
  • 7
intore
  • 399
  • 1
  • 6
  • 13
  • you might find some help here: https://stackoverflow.com/questions/26675681/bash-how-to-check-the-exit-status-using-an-if-statement – Kiwy Feb 16 '18 at 12:40

3 Answers3

20
if [ "$i" -eq 4 ] && command1; then
   echo 'All is well'
else
   echo 'i is not 4, or command1 returned non-zero'
fi

With $(command) -eq 0 (as in your code) you test the output of command rather than its exit code.

Note: I've used command1 rather than command as command is the name of a standard utility.

Kusalananda
  • 320,670
  • 36
  • 633
  • 936
9

$(somecmd) would capture the output of somecmd, if you want to check the exit code of a command, just put it in the condition part of the if statement directly

i=4
if [[ $i -eq 4 ]] && false ; then
     echo this will not print
fi
if [[ $i -eq 4 ]] && true ; then
     echo this will print
fi
ilkkachu
  • 133,243
  • 15
  • 236
  • 397
3

To capture the exit code, use $? after (immediately, before executing any other command) executing the command. Then you can do things like

ls /proc/$PPID/fd
ls=$?
if test $ls != 0; then
  echo "foo failed"
  if test $ls = 2; then
    echo "  quite badly at that"
  fi
fi

I.e. you can evaluate expressions involving the exit code multiple times.