How to exit from a Linux terminal if a command failed?

It is a common scenario that certain commands that we write might fail for some reason. The reasons can be many, it can either be because of the difference between the GNU and BSD version of the core utils, or simply because there’s something logically wrong. In such a case, if we want to terminate the process without having to make use of the explicit technique of CTRL + C then we have a couple of different options.

Using bash exit command with ||

Let’s say that we have a certain command my_command that is running perfectly on Ubuntu but on Mac OS X, and you want to make sure that if it fails for some particular reason, then the process should be terminated and the terminal should exit.

In that case, we can make use of the command shown below.


my_command || { echo 'my_command isn't working!' ; exit 1; }

This command will make sure that the terminal exits if and only if the command isn’t working.

Using $

Another command that one can make use of is shown below.


if [ $? -eq 0 ]
   echo "it works perfectly"
   echo "it isn't working"

In the above command, we are making use of the fact that if the command returns a non-zero exit code, then we echo it, and then we can exit from the terminal.

Using set -e

If you are running the command using a bash script, then you can insert the following command at the top of your script.


set -e

Putting the above command on top of your bash script will cause the script to exit if any commands return a non-zero exit code.