Possible Duplicate:
Identifying received signal name in bash shell script
When using something like trap func_trap INT TERM EXIT
with:
func_trap () { ...some commands... }
Is there a way in the function block to detect which trap has called it?
Something like:
func_trap () { if signal = INT; then # do this else # do that fi }
Or do I need to write a separate function for each trap type that does something different? Is there a bash variable that holds the latest received signal?
Thanks in advance!
The secret sauce is a pseudo-signal provided by bash, called EXIT, that you can trap; commands or functions trapped on it will execute when the script exits for any reason.
Trap allows you to catch signals and execute code when they occur. Signals are asynchronous notifications that are sent to your script when certain events occur. Most of these notifications are for events that you hope never happen, such as an invalid memory access or a bad system call.
Description. trap defines and activates handlers to run when the shell receives signals or other special conditions. ARG is a command to be read and executed when the shell receives the signal(s) SIGNAL_SPEC.
A built-in bash command that is used to execute a command when the shell receives any signal is called `trap`. When any event occurs then bash sends the notification by any signal. Many signals are available in bash. The most common signal of bash is SIGINT (Signal Interrupt).
To trap a signal any time during the execution of a shell script, define a trap statement at the start of the script. Alternatively, to trap a signal only when certain command lines are to be executed, you can turn on the trap statement before the appropriate command lines and turn off the trap statement after the command lines have been executed.
The most common signal of bash is SIGINT (Signal Interrupt). When the user presses CTRL+C to interrupt any process from the terminal then this signal is sent to notify the system. How you can use trap command to handle different types of signals is explained in this tutorial.
Set `trap` command for SIGTERM in a script SIGTERM signal is used to terminate the process immediately by releasing its resources. Create a bash file named ‘ trapscript.sh ’ with the following code. An infinite for loop is declared in the script that will print a text continuously until SIGTERM signal occurs.
You can implement your own trap function that automatically passes the signal to the function:
trap_with_arg() { func="$1" ; shift for sig ; do trap "$func $sig" "$sig" done } $ trap_with_arg func_trap INT TERM EXIT
The first argument to func_trap will be the name of the signal.
No documentation hints of any argument or variable holding the signal that was trapped, so you'll have to write a function/trap statement for each trap you want to behave differently.
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