The Shell Scripting Tutorial


Trap die tip (!)

A smart way to trap error conditions

14 May 2015

A useful technique in shell scripting is the set -e (or sh -e) option. This causes the script to exit on any error. However, the downside to this is that you don't get the chance to display any kind of error message, particularly if the failing command doesn't cause any output of its own in an error situation.

Using "trap die ERR" (the function doesn't have to be called "die", it can be anything you like, of course) allows you to get your own custom die() function to be called before the script falls over.

In this exampe script, the echo and true statements succeed, but false fails, causing the die() function to be called, and the echo Done never happens.

Download trap-die.sh script
#!/bin/bash

trap die ERR

die()
{
  echo "Failed in script \"$0\" at line $BASH_LINENO"
  exit 1
}

echo Hello
true
echo This is a test
false # This command always fails
echo Done
exit 0

You can see the outcome by running the script:

trap 1

By running the script via bash -x, you get to see exactly where the script fails:

trap 2


My Paperbacks and eBooks

My Shell Scripting books, available in Paperback and eBook formats. This tutorial is more of a general introduction to Shell Scripting, the longer Shell Scripting: Expert Recipes for Linux, Bash and more book covers every aspect of Bash in detail.

Shell Scripting Tutorial

Shell Scripting Tutorial
is this tutorial, in 88-page Paperback and eBook formats. Convenient to read on the go, and in paperback format good to keep by your desk as an ever-present companion.

Also available in PDF form from Gumroad:Get this tutorial as a PDF
Shell Scripting: Expert Recipes for Linux, Bash and more

Shell Scripting: Expert Recipes for Linux, Bash and more
is my 564-page book on Shell Scripting. The first half covers all of the features of the shell in every detail; the second half has real-world shell scripts, organised by topic, along with detailed discussion of each script.