Final goal: BASH script, waiting for the completion of background jobs, is not interrupted at the first Ctrl-c ; instead, a second Ctrl-c required to exit.
I know well how the BASH -builtin trap works. You can:
Use it to completely ignore the signal (e.g. trap '' 2 ) ... or
Use it to execute arbitrary commands before the original signal function is allowed (for example, trap cmd 2 , where cmd is executed before the parent script is interrupted due to SIGINT ).
So, the question boils down to the following:
How can I effectively combine 1 and 2 , i.e. prevent the end result that will lead to a signal ( 1 - for example, stop script cancellation due to SIGINT ), and also do something else ( 2 ), for example, increase the counter, check the counter and conditionally either print a warning or exit).
Simply put:
How can I make a signal, do something else completely; don't just insert a task before it does its job.
Here is a sample code to demonstrate what I'm aiming for; however, it certainly does not work, because trap can only execute 1 or 2 on top.
#!/bin/bash declare -i number_of_times_trap_triggered cleanup_bg_jobs() { number_of_times_trap_triggered+=1 if [[ ${number_of_times_trap_triggered} -eq 1 ]]; then echo "There are background jobs still running" echo "Hit Ctrl-c again to cancel all bg jobs & quit" else echo "Aborting background jobs" for pid in ${bg_jobs}; do echo " Killing ${pid}"; kill -9 ${pid}; done fi } f() { sleep 5m; } trap cleanup_bg_jobs 2 bg_jobs= for job in 1 2 3; do f & bg_jobs+=" $!" done wait
So this is the result that you get when you press Ctrl-c once.
[rsaw:~]$ ./zax ^CThere are background jobs still running Hit Ctrl-c again to cancel all bg jobs & quit [rsaw:~]$ ps axf|tail -6 24569 pts/3 S 0:00 /bin/bash ./zax 24572 pts/3 S 0:00 \_ sleep 5m 24570 pts/3 S 0:00 /bin/bash ./zax 24573 pts/3 S 0:00 \_ sleep 5m 24571 pts/3 S 0:00 /bin/bash ./zax 24574 pts/3 S 0:00 \_ sleep 5m
Of course, I could change this to clear the tasks on the first Ctrl-c , but thatβs not what I want. I want to stop BASH from quiting after starting the first trap ... until it is called a second time.
PS: The target platform is Linux (I didn't care about POSIX compliance) using BASH v4 +