/ tech

How Do I Trap Exit in a Shell Script?

Often times it is necessary to do things that need to be cleaned up when a shell script exits, remove temporary files for instance. Cleanup should occur when the script exits normally or when it is interrupted. Interruptions can be a BREAK (usually ^C), entered by the user, or other signals which can occur for various reasons. Ignoring the more complex things, just cleaning up after ^C is entered and exiting the script keeps things tidy without much hassle.

Adding these few lines at the top of your shell script will handle ^C and EXIT (the script ending normally) or just EXIT, properly.

#!/bin/bash

exithandler() { echo "done"; }
bye() { echo "bye"; exit 1; }

trap exithandler EXIT
trap bye SIGINT

read -p'waiting... ' a

Here's what happens just running this script and pressing RETURN:

$ ./trapme.sh
waiting...
done

Here's what happens when pressing ^C:

$ ./trapme.sh
waiting... bye
done
How Do I Trap Exit in a Shell Script?
Share this