How to run a command when interrupting a shell script?

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

+5
source share
2 answers

Although this can come as a shock to many, you can use the built-in trap trapfor traps :-)

Well, at least those that can be captured, but CTRL-C is usually attached to the signal INT. You can capture signals and execute arbitrary code.

script , . , INT, :

#!/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.

( , CTRL-C 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!!
+7

trap , SIGINT, Ctrl-C.

+3

All Articles