I want to execute some commands at the end of a bash script, even if the user presses CTRL + C to cancel its execution.
I know that I can run a bash script from another programming language (e.g. Python) so that I can use the finally (try-finally) block to execute some code.
But knowing that StackOverflow is the center for sharing fabulous ideas, I ask if there is a way to do what I want from my bash script.
So, ideas?
EDIT:
I want to kill every process open in my bash projects, i.e. selenium and xvfb.
I tried to write this to code:
trap "selenium_pids=$(ps ux | awk '/selenium/ && !/awk/ {print $2}');for pid in $selenium_pids; do kill -9 $pid;done; xvfb_pids=$(ps ux | awk '/Xvfb/ && !/awk/ {print $2}'); for pid in $xvfb_pids; do kill -9 $pid; done" EXIT
But this obliges me to repeatedly press "CTRL + C", each time I run the subprocess from inside my script, something like:
Testing nsi.bd.helpcenter ...^C: -- Total time: 0min 0seg
Testing nsi.bibliography ...^C: -- Total time: 0min 0seg
Testing nsi.digitallibrary ...^C: -- Total time: 0min 0seg
Testing nsi.digitallibraryinstaller ...^C: -- Total time: 0min 1seg
Testing nsi.digitallibraryskins ...^C: -- Total time: 0min 0seg
....#continues
Changing the trap line finale from EXIT to SIGINT, for example:
trap "selenium_pids=$(ps ux | awk '/selenium/ && !/awk/ {print $2}');for pid in $selenium_pids; do kill -9 $pid;done; xvfb_pids=$(ps ux | awk '/Xvfb/ && !/awk/ {print $2}'); for pid in $xvfb_pids; do kill -9 $pid; done" SIGINT
.
CTRL + C?
"exit 1" ,
trap "... ;exit 1"
, CTRL + C, , .
?