3

To check the exit code of command in Bash the following logic is used:

if [ $? -ne 0 ]
then
    echo "Error occurred"
    return 1
fi

My problem is that adding this after every command makes the script very long with multiple copies of the same thing, and very hard to maintain.

The best thing here would be a function, that would be called from all the locations the the exit code needs to be checked. The problem is that the exit command can not be used, because it will kill current process (current Bash session will be killed), so only the return command can be used. But when using the return command, in a called function, the calling function must still check the exit code, and were back to the same problem.

Is there any thing like MACRO in Bash or any other way to the error checking more efficient?

2
  • How about set -e? Commented Dec 22, 2016 at 10:22
  • It will kill current process, and that is not the required behavior Commented Dec 22, 2016 at 10:28

1 Answer 1

1

Instead of this:

somecommand
if [ $? -ne 0 ]
then
    echo "Error occurred"
    return 1
fi

You don't need to write conditions on the $? variable, you can use the command itself in if statements:

if ! somecommand
then
    echo "Error occurred"
    return 1
fi

Another alternative is to create a helper function to encapsulate the action on error, and use the || operator after the command to call the function and then return 1 after:

error() {
    echo "Error occurred"
}

somecommand || { error; return 1; }

Finally, if you don't really need return 1 and you don't mind to exit the script in case of failure, then you can exit 1 inside the helper function and then the caller code can become more compact:

fatal() {
    echo "Error occurred"
    exit 1
}

somecommand || fatal
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you!! the operator || choice looks good, one line instead of 4 every time
@A.David thanks, but if I'm right, they why you still haven't marked it the accepted answer?

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.