5

Consider the case where I have a very long bash script with several commands. Is there a simple way to check the exit status for ALL of them easily. So if there's some failure I can show which command has failed and its return code.

I mean, I don't want to use the test for each one of them checks like the following:

my_command
if [ $status -ne 0 ]; then
    #error case
    echo "error while executing " my_command " ret code:" $?
    exit 1
fi
2
  • 1
    Is there a point of continuing once a command failed? Often than not tasks depend on each other. Commented Oct 7, 2015 at 11:05
  • No, I would like to stop the execution, cleanup and show a user friendly exit statement Commented Oct 7, 2015 at 12:20

3 Answers 3

5

One can test the value of $? or simply put set -e at the top of the script which will cause it to exit upon any command which errors.

#!/bin/sh

set -xe

my_command1

# never makes it here if my_command1 fails
my_command2
Sign up to request clarification or add additional context in comments.

2 Comments

The way I program is to use set -xe for everything, and exit upon first error reporting all commands to the user. I updated the post to reflect this.
If you want to hard wire a command to not trigger the program to exit upon error while under set -xe use: bad_command || true
4

You can do trap "cmd" ERR, which invokes cmd when a command fails. However this solution has a couple of drawbacks. For example, it does not catch a failure inside a pipe.

In a nutshell, you are better off doing your error management properly, on a case by case basis.

1 Comment

Is there some simple method in this case to show the failing command?
2

You can write a function that launches:

function test {
    "$@"
    local status=$?
    if [ $status -ne 0 ]; then
        echo "error with $1" >&2
    fi
    return $status
}

test command1
test command2

1 Comment

this seems copied from stackoverflow.com/a/5195741/862225, no? If true, it would be nice to add a reference

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.