Three ways to die and echo the cause in your bash script, choose one

If a line in your bash script returns with code 1, and not 0, you want the script to stop execution and clearly blurt out, or echo, the offending line.

Not doing so can cause significant pain for your clients, for example in an enterprise deployment environment, so choose a method and use it with the goal being proper error handling and pain reduction. As a confession, I have written scripts that where not bullet proof, in a continous integration environment, the consequence was that Jenkins job clients could not trust the blue outcome (or green if you are using the green balls plugin), so this post is in part my own aide memoire.

The overarching consideration is that writing a bash script requires the same care and skill as any other program that you may write, perhaps even more so than say a strongly typed language such as Java.

The three methods can be found below, choose what works for you.

#!/bin/bash

# Three methods to echo what killed your script, in other words, 
# methods that can be used to echo the last command run and 
# exit with bash

####################### run() method ########################

 die() { echo >&2 -e "\nRUN ERROR: $@\n"; exit 1; }
	
 run() { $*; code=$?; [ $code -ne 0 ] && die "command [$*] failed with error code $code"; }

 echo "1. COMPACT METHOD: run() based"

 run ls /opt

 # TODO: uncomment the next two lines to test the run() method

 # echo "COMPACT METHOD: run() based"
  
 # run ls /wrong-dir
 
###################### trap return code method ############################

 echo "2. VERBOSE METHOD: trap based"

 trap 'previous_command=$this_command; this_command=$BASH_COMMAND' DEBUG

 # TODO: uncomment the next two lines to test the trap return code method

 # ls /wrong-dir

 cmd=$previous_command ret=$?

 if [ $ret -ne 0 ]; then 
	echo "command[$cmd] failed with error code $ret"; 
 fi

####################### trap EXIT method ####################################

 echo "3. COMPACT METHOD: trap based"

 set -e 

 trap 'echo "exit $? due to $previous_command"' EXIT

 ls /foo-bar

Finally, credit to stackoverflow and the individuals in the following reference thread.

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s