Skip to main content
Bash ScriptingCentOS

Using TRAP to handle interrupts within your BASH script

By April 16, 2013No Comments

Having driven ourselves loopy for a few lessons now we have to handle interruptions. Making a script robust may include ensuring that certain activities always happen before the script closes; or perhaps, ensuring that only one instance of a script is running at a time. This would normally require that as the script starts we create a file and check for that file existing. Of course, though, we will then need to ensure the file is deleted.

This and more can be handled by the command trap. First we we look at using the variable $$ so we can determine the process id or PID of the script. This could be useful As one script had to start a script and stop it. To stop the controlling script we would have to know the PID of the script that it started.

		FILE=/tmp/$(basename $0).pid
		echo $$ > $FILE

Here we create a file based on the filename of the script and add a .pid extension. The file contains the PID of the running script.
To kill the script we could issue the command: kill -9 -$(cat /tmp/, assuming the original script was named

To test that the PID file does not exist before running anything in the script, this might be to control file locking, then we could add this test to the script:

if [ -e $FILE ]
		echo "$FILE exists so script must exit"
		exit 2

Now we can check for the file we should ensure it is deleted when the script exits; for this, we use trap and look for the exit command in the script. When exit is executed we can run commands we specify within the trap arguments.

trap ‘rm -f $FILE; ‘ EXIT

Here the trap commands are enclosed in single quotes, followed by the signal we want to trap, in this case, a script EXIT . With this in place if the file exists when the script runs it will be deleted by our IF block that runs exit 2. At the end of the script we run exit 0; so on correct execution of the script the file will also be deleted.