Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 416
Jatin Bodarya Avatar asked Feb 05 '13 07:02

Jatin Bodarya


People also ask

How do you exit a script if command fails?

Exit When Any Command Fails This can actually be done with a single line using the set builtin command with the -e option. Putting this at the top of a bash script will cause the script to exit if any commands return a non-zero exit code.

How do you terminate a shell script?

To end a shell script and set its exit status, use the exit command. Give exit the exit status that your script should have. If it has no explicit status, it will exit with the status of the last command run.

Can you modify a bash script while it is running?

with the current version of bash, modifying a script on-disk while it is running will cause bash to "try" to load the changes into memory and take these on in the running script. if your changes come after the currently executing line, the new lines will be loaded and executed.

How do I terminate a bash command?

There are many methods to quit the bash script, i.e., quit while writing a bash script, while execution, or at run time. One of the many known methods to exit a bash script while writing is the simple shortcut key, i.e., “Ctrl+X”. While at run time, you can exit the code using “Ctrl+Z”.


1 Answers

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!!
like image 132
paxdiablo Avatar answered Oct 19 '22 23:10

paxdiablo