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

LinuxOperating SystemOpen Source

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.

Command

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. Command my_command if [$? -eq 0 ]
then
echo "it works perfectly"
else
echo "it isn't working"
fi

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.

Command

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.

Published on 29-Jul-2021 11:55:26