Take this script
#!/bin/sh
fd ()
{
echo Hello world
exit
}
trap fd EXIT INT
for g in {1..5}
do
echo foo
sleep 1
done
I would like fd
to fire once, either from Control-C or if the script exits normally. However if you hit Control-C it will run twice. How can I fix this?
The exit signal is a bash builtin and can be used to catch any signal. For all intents and purposes, if you trap exit, it will be executed when the shell process terminates. Exit the shell, returning a status of n to the shell's parent. If n is omitted, the exit status is that of the last command executed.
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”.
An exit status code is returned when any Linux command is executed from the terminal, either the command is successful or unsuccessful. This status code can be used to show the error message for unsuccessful execution or perform any particular task by using shell script.
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.
Do cascading traps. exit 127
will run the EXIT
trap and set the exit code to 127, so you can say
#!/bin/sh
fd () {
echo Hello world
# No explicit exit here!
}
trap fd EXIT
trap 'exit 127' INT
I remember learning this from other people's scripts after struggling with various workarounds to your problem for several years. After that, I have noticed that some tutorials do explain this technique. But it is not documented clearly in e.g. the Bash manual page IMHO. (Or it wasn't when I needed it. Maybe some things don't change in 15 years ... :-)
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