How to use Ctrl+C to kill all background processes started in a Bash script?
Update: trap
requires removing SIG
prefix on condition, although some shells support including it. See comment below.
The ampersand "&" runs a command in the background in a new process. When its parent process (the command that runs the bash script in your case) ends, this background process will reset its parent process to init (process with PID
1), but will not die. When you press ctrl+c
, you are sending an interrupt signal to the foreground process, and it will not affect the background process.
In order to kill the background process, you should use the kill
command with the PID
of the most recent background process, which could be obtained by $!
.
If you want the to use ctrl+c
to kill both the script and background process, you can do this:
trap 'kill $BGPID; exit' INT
sleep 1024 & # background command
BGPID=$!
sleep 1024 # foreground command of the script
trap
modifies the trap handler of the SIGINT
(trap
requires removing the SIG
prefix but some shell may support including it) so the script will kills the process with $BGPID
before it exits.