Bash: Finally (Exclude) Exception

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, , .

?

+3
2

, :

finalize_xvfb_and_selenium() {
    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
}

finalize_xvfb_and_selenium_and_exit() {
    finalize_xvfb_and_selenium
    echo -e "\n\nXvfb and seleniumrc finalized. Exiting ..."
    exit 13
}

#trap (CTRL+C) signal, to finalize proccess running before exit
trap finalize_xvfb_and_selenium_and_exit SIGINT

, , kill -9 .

+8

.

control-c , SIGINT . . , , , .

, . , SIGKILL, kill -9.


: bash . , ps. , - (, SIGUSR1), , .

, , . , , .

+6

Source: https://habr.com/ru/post/1770824/


All Articles