It is common to run more commands when a command has run successfully, for example:


grep 'IMPORTANT LINE' INPUT_FILE > /dev/null
if (( $? == 0 )); then
do_something
fi

The code above has nothing wrong with it. It checks the Exit Status $?, you may see the checking using [[ $? -eq 0 ]], both do the job well. If exit status is zero, which means the command exits with success, then the script do something.

However there is a way to code it little more efficient, that is:


if grep 'IMPORTANT LINE' INPUT_FILE > /dev/null; then
do_something
fi

The if actually and only checks the exit status and that’s how it works, it does not know anything about string comparison, integer, file existence, or whatsoever. The only thing it knows is whether the exit status is 0 or not.

Using (( $? == 0 )) is redundant and unnecessary. (( )) and [[ ]] are called Compound Command, thus they are commands, they exits with 0 or 1 exit status like most of commands. Hence you can just put a command after if.

If you want to run commands when a command fails, you only need to prefix ! before that command, for example:


if ! grep 'IMPORTANT LINE' INPUT_FILE > /dev/null; then
do_something_when_no_IMPORTANT_LINE
fi

1   Further reading

  • help if
  • Lists and if in Compound Commands in man bash
  • Bash if conditional statement, which I wrote a few weeks ago, explains more about if and little while.