bash: Trap error and exit

I’ve been working with a bash script which monitors different processes. If it detects any error then trigger alert and exit. While working there, I noticed there are different ways to do this e.g. set and trap

Bash functions, unlike functions in most programming languages, do not allow to return a value to the caller. Although bash has a return statement, the only thing we can specify with it is the function’s status, which is a numeric value like the value specified in an exit statement. The status value is stored in the $? variable. If a function does not contain a return statement, its status is set based on the status of the last statement executed in the function. To actually return arbitrary values to the caller we must use other mechanisms. The simplest way is to set a global variable with the result. But what if we don’t want to reset the status in every trapped error and want to abort the script immediately when an error is trapped?

set -e: Exit immediately if a command exits with a non-zero status. set -e was an attempt to add “automatic error detection” to the shell. Its goal was to cause the shell to abort any time an error occurred, so we don’t have to put || exit 1 after each important command. But it’s not very reliable and considered as a bad practice.
trap is a better alternative and its proper implementation works with any level of function nesting, any flow.

Here, this alert function sends a TERM signal back to the top level shell, which is caught and handled using the provided command, in this case, exit 1.

References: set -e is not very reliable and considered as a bad practice, Why doesn’t set -e do what I expected?, Returning Values from Bash Functions, Register the top level shell for the TERM signal to exit, and then send a TERM to the top level shell, Exit shell script from a subshell

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s