I was doing some research to figure out how to easily kill a Linux process given part of it’s name. It’s fairly simple to do it manually, but if you didn’t already know, programmers are lazy.
The first thing I was doing…
ps aux | grep Foo
find the process ID (PID) with my eyes, and then kill it…
kill -9 123456
Next, I started finding complex piped commands to find and extract the PID. For instance…
pid=`ps -eo pid,args | grep Foo | grep -v grep | cut -c1-6`
and slightly simpler…
ps aux | grep Foo | grep -v grep | awk ‘{print $2}’
Finally, I discovered pgrep and pkill. There are quite a few options for each command, but simply put:
To get the PID for a process with a name containing ‘Foo’…
pgrep Foo
To get the PID for a process with a command line containing ‘Bar’ (as in > Foo -n Bar)…
pgrep -f Bar