RSS Feed Share on Twitter

All Shell Scripting Tips

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.

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

 

 


You can buy the content of this tutorial as a PDF to download to all of your devices!

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!