Created
August 3, 2020 09:53
-
-
Save digitalist/c0349ab51633f0ff0211d3ad6fe5c442 to your computer and use it in GitHub Desktop.
a bash example on traps, background processes and arrays as function args
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# en: an example of killing background tasks using ctrl+c from bash | |
# useful when you need to start/kill a bunch of services | |
# ru: пример работы с убиваемыми по ctrl-c фоновыми задачами в баш-скрипте | |
# полезно, когда надо перезапускать много задач в фоне, например серверов | |
function ctrl_c() { # trap ctrl-c and call ctrl_c() | |
echo "** Trapped CTRL-C" | |
arr=("$@") #take first arg, it's an array | |
for i in "${arr[@]}"; | |
do | |
echo "killing ${i}" | |
kill $i | |
done | |
} | |
echo '=> starting first background task [sleep 60 &]' | |
sleep 60 & # fake some long running process, could be: python2 server.py & | |
TASK1_PID=$! # take a process PID | |
echo '=> starting second background task [sleep 180 &]' | |
sleep 180 & | |
TASK2_PID=$! | |
echo "=> command1 PID is ${TASK1_PID}" | |
echo "=> command2 PID is ${TASK2_PID}" | |
PIDS_TO_KILL=("${TASK1_PID}" "${TASK2_PID}") #make an array of pids | |
trap 'ctrl_c "${PIDS_TO_KILL[@]}"' INT #set a trap | |
# trap "ctrl_c 1 " INT #reboot with sudo lol, kills process 1 | |
wait | |
echo '...done' | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment