Coder Perfect

What should I do if a command fails? [duplicate]

Problem

I’m new to shell scripting. If a command fails, I want to produce a message and quit my script. I’ve attempted:

my_command && (echo 'my_command failed; exit)

However, it does not function. It continues to carry out the instructions after this line in the script. Ubuntu and bash are my operating systems.

Asked by user459246

Solution #1

Try:

my_command || { echo 'my_command failed' ; exit 1; }

Four changes:

You need a || rather than a && because you only want to print the message and leave when the command fails (exits with a non-zero value).

cmd1 && cmd2

cmd2 will be run if cmd1 is successful (exit value 0). In contrast,

cmd1 || cmd2

cmd2 will be run if cmd1 fails (exit value non-zero).

When you use (), the command inside them runs in a sub-shell, and when you call exit from there, you exit the sub-shell rather than your original shell, so execution continues in your original shell.

To get around this, utilize

Bash need the final two adjustments.

Answered by codaddict

Solution #2

Although the previous responses have adequately addressed the direct question, you might also be interested in using set -e. Any command that fails (outside of particular contexts such as if tests) will result in the script aborting. It’s quite beneficial for some scripts.

Answered by Daenyth

Solution #3

Simply add if you want that behavior for all commands in your script.

set -e 
set -o pipefail

at the outset of the script When a command produces a non-zero exit code, this set of options tells the bash interpreter to exit. (See http://petereisentraut.blogspot.com/2010/11/pipefail.html for further information on why pipefail is required.)

However, you will not be able to print an exit message using this method.

Answered by damienfrancois

Solution #4

Also, the exit status of each command is saved in the shell variable $?, which you can examine immediately after running it. Failure is indicated by a non-zero status:

my_command
if [ $? -eq 0 ]
then
    echo "it worked"
else
    echo "it failed"
fi

Answered by Alex Howansky

Solution #5

I came up with the following idiom:

echo "Generating from IDL..."
idlj -fclient -td java/src echo.idl
if [ $? -ne 0 ]; then { echo "Failed, aborting." ; exit 1; } fi

echo "Compiling classes..."
javac *java
if [ $? -ne 0 ]; then { echo "Failed, aborting." ; exit 1; } fi

echo "Done."

Each command should be preceded by an instructive echo, and each command should be followed by the same if [$? -ne 0];… line. (Of course, if you wish, you can change the error message.)

Answered by Grant Birchmeier

Post is based on https://stackoverflow.com/questions/3822621/how-to-exit-if-a-command-failed