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?
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.
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.
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.
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”.
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!!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With