Kill (9-TERM) Processes with Expression(s) in Name or Call#

I often find myself needing to terminate processes containing certain string literals or whose call matches a given regular expression. For that reason I probably re-write and tweak this one-liner several times a month; which is why I’m putting it out there.

One-Liner#

REPLACE, as is usual with grep, can be just a string literal or a regular expression. Use this command with caution as you might kill processes you didn’t intend to.

⚠️ Make sure the output of ps | grep only contains processes you want to terminate as shown below.

ps -fea |\
grep -e 'REPLACE' |\
grep -v 'grep' |\
tr -s ' ' '|' |\
cut -d'|' -f2 |\
xargs -I{} kill -9 {}

Breakdown#

Dummy Processes#

Executing four watch ls processes and keeping them running in the background.

$ watch ls & watch ls & watch ls & watch ls &
[1] 2494555
[2] 2494556
[3] 2494557
[4] 2494558

Filtering Processes#

$ ps -fea | grep 'watch.*ls' | grep -v 'grep'
user 2494555    6880  0 14:40 pts/17   00:00:00 watch ls
user 2494556    6880  0 14:40 pts/17   00:00:00 watch ls
user 2494557    6880  0 14:40 pts/17   00:00:00 watch ls
user 2494558    6880  0 14:40 pts/17   00:00:00 watch ls

Retrieving Process IDs#

$ ps -fea | grep 'watch.*ls' | grep -v 'grep' | tr -s ' ' '|' 
user|2494555|6880|0|14:40|pts/17|00:00:00|watch|ls
user|2494556|6880|0|14:40|pts/17|00:00:00|watch|ls
user|2494557|6880|0|14:40|pts/17|00:00:00|watch|ls
user|2494558|6880|0|14:40|pts/17|00:00:00|watch|ls
$ ps -fea | grep watch | tr -s ' ' '|' | cut -d'|' -f2
2494555
2494556
2494557
2494558

Result#

$ ps -fea | grep watch | tr -s ' ' '|' | cut -d'|' -f2 | xargs -I{} kill -9 {}
$
$ ps -fea | grep 'watch.*ls' | grep -v 'grep'
$