12

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?

codeforester
  • 39,467
  • 16
  • 112
  • 140
Jatin Bodarya
  • 1,425
  • 2
  • 20
  • 32

2 Answers2

23

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!!
codeforester
  • 39,467
  • 16
  • 112
  • 140
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
3

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

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358