Q:

How to fire a command when a shell script is interrupted?

I want to fire a command like " rm -rf /etc/XXX.pid"  when the shell script is interrupted in the middle of its execution. Like using CTRL+C
Can anyone help me what to do here?

A:

Although it may come as a shock to many, you can use the bash built-in trap to trap signals :-)
Well, at least those that can be trapped, but CTRL-C is usually tied to the INT signal. You can trap the signals and execute arbitrary code.
The following script will ask you to enter some text then echo it back to you. If perchance, you generate an INT signal, it simply growls at you and exits:
#!/bin/bash

exitfn () {
    trap SIGINT              # Restore signal handling for SIGINT
    echo; echo 'Aarghh!!'    # Growl at user,
    exit                     #   then exit script.
}

trap "exitfn" INT            # Set up SIGINT trap to call function.

read -p "What? "             # Ask user for input.
echo "You said: $REPLY"

trap SIGINT                  # Restore signal handling to previous before exit.

A test run transcript follows (a fully entered line, a line with pressing CTRL-C before any entry, and a line with partial entry before pressing CTRL-C):
pax> ./testprog.sh 
What? hello there
You said: hello there

pax> ./testprog.sh 
What? ^C
Aarghh!!

pax> ./qq.sh
What? incomplete line being entere... ^C
Aarghh!!

A:

trap is used to catch signals in scripts, including the SIGINT generated when Ctrl-C is pressed.

