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.

Advertisements

Search your source with wcgrep -l methodname

Having used, for years, the inferior command

$grep -rin 'methodname' .

when recursively searching through files for a method, the discovery of

wcgrep -l methodname

comes as a shock.

Looks like I’m not the only one using $grep -rin. In any case, there is a new, clever kid on the block, freshly installed in /usr/bin: wcgrep -l methodname

It is smart enough not to search Subversion’s text-base files, something that has plagued me, and perhaps you too. For an entertaining post on the topic, read this post on justinsomnia.org, published six years ago, ouch, that rubs some serious salt into the wound.

You can find the wcgrep script HERE.