Thursday, July 23, 2015

One line shell command to kill processes that match a search string...

I had a bunch of java processes running on a server, and I needed to kill all of them. It's easy enough to write a shell script to kill them, but I wanted to do it all in one command.  It is common enough to do, so I did a search on stackoverflow and found what I needed:

for pid in `ps x | grep java | grep -v grep | awk '{print $1}'` ; do kill -9 $pid ; done

The key is the command in the back ticks.  The shell will execute that first, and use the results in the for loop - reading each result into the variable $pid.