8

This question already has an answer here:

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.

marked as duplicate by Jeff Schaller, dhag, X Tian, Stephen Kitt, Raphael Ahrens Feb 16 '18 at 15:54

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

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.

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
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.

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