How can one extract the exit code of a command?

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.


$(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

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.