How to create efficient error checking in Bash script?

196 views Asked by At

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?

1

There are 1 answers

2
janos On

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