<<< Back to Tips Index

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

Invest in your career. Buy my Shell Scripting Tutorial today:

 

Steve's Bourne / Bash shell scripting tips
Share on Twitter Share on Facebook Share on LinkedIn Share on Identi.ca Share on StumbleUpon
Join the Facebook page for more tips and tricks:


Buy my Shell Scripting Tutorial

(Free Sample)
(more info)

$9.99 US Dollars

£4.99 UK Pounds

€6.99 Euros