Buy this tutorial as a PDF for only $5
14 May 2015
Trap die tip
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.
#!/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:

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

Appreciate this site? Please consider making a donation:
Books and eBooks
My Shell Scripting books, available in Paperback and eBook formats.
![]() Shell Scripting Tutorial is this tutorial, in 88-page Paperback and eBook formats. Convenient to read on the go, and to keep by your desk as an ever-present companion. | ![]() Shell Scripting: Expert Recipes for Linux, Bash and more is my 564-page book on Shell Scripting. The first half explains the features of the shell; the second half has real-world shell scripts, organised by topic, with detailed discussion of each script. |
Contact
You can mail me with this form. If you expect a reply, please ensure that the address you specify is valid. Don't forget to include the simple addition question at the end of the form, to prove that you are a real person!