bashshellshinterrupt-handling

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?


Solution

  • 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 (it can be changed with stty but let's discount that possibility for simplicity).

    You can therefore trap the signals and execute arbitrary code. For example, 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 SIGINT trap to call function.
    
    read -p "What? "         # Ask user for input,
    echo "You said: $REPLY"  #   then echo back.
    
    trap SIGINT              # Restore signal handling.
    

    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!!