How to Kill All Background Jobs
You are at the end of a productive session and now you just want to clean up all your background processes. But you can’t think of an easy way to get rid of all those pesky processes.
Working Example
Here’s an example of the processes I wanted to kill.
❯ jobs -p
[1] 74833 suspended nvim file.py
[2] 80770 suspended nvim file.py
[3] 15257 suspended nvim file.py
[4] 54634 suspended nvim file.py
[5] 8107 suspended nvim file.py
[6] 25686 suspended nvim file.py
[7] 37739 suspended nvim file.py
[8] 70741 suspended nvim file.py
[9] - 74222 suspended nvim file.py
[10] + 82424 suspended nvi file.pym
There’s no way I’m going to run kill -9 $pid
on all of those processes one by one.
The top answer on Stack Overflow seems promising but kill $(jobs -p)
doesn’t work when the output is like the one above. The weird spaces and pesky +/- signs get in the way.
Let’s get rid of them.
❯ jobs -p | tr -d '+-'| tr -s ' ' | cut -d' ' -f2 | xargs -I{} kill -9 {}
Explanation
- List all background jobs
- | remove all +/- symbols (
tr -d '-+'
doesn’t work as+
is treated as a flag ) - | squeeze multiple spaces into one
- | extract the process id
- | sequentially kill each process