Does this look familiar?:
ps aux|grep "YOUR_PROGRAM --WITH-SOME-SPECIAL-SWITCHES"
1000 28319 0.0 2.6 54884 47340 ? S Feb16 0:01 YOUR_PROGRAM --WITH-SOME-SPECIAL-SWITCHES
1000 28330 0.0 2.6 54880 47360 ? S Feb16 0:01 YOUR_PROGRAM --WITH-SOME-SPECIAL-SWITCHES
1000 28347 0.0 2.6 54884 47336 ? S Feb16 0:01 YOUR_PROGRAM --WITH-SOME-SPECIAL-SWITCHES
kill 28319
kill 28330
kill 28347
If it does then STOP! Use this one-liner instead to kill all processes matching YOUR_PROGRAM –WITH-SOME-SPECIAL-SWITCHES:
ps|grep -v grep|grep "YOUR_PROGRAM --WITH-SOME-SPECIAL-SWITCHES"|awk '{print $1}'|xargs kill
Here’s what the one-liner does:
1. ps Outputs all processes you’re running.
2. grep -v grep Matches any data piped (|) in other than “grep”. This prevents the one-liner from trying to kill the running grep command.
3. grep "YOUR_PROGRAM --WITH-SOME-SPECIAL-SWITCHES" Matches only output with your YOUR_PROGRAM –WITH-SOME-SPECIAL-SWITCHES in it.
4. awk '{print$1}' Select the first column of data from the previously matched output, in this case the PID (process ID).
5. xargs kill calls kill for each PID.
Note: If your want to kill _all_ processes running and not just a subset (i.e. –WITH-SOME-SPECIAL-SWITCHES) you can use killall YOUR_PROGRAM
In summary, if you find yourself killing similar processes one at a time, use this simple one-liner to kill them all at once. Also you could turn this into a simple shell script.
2 Comments
Nice, thanks for this. I need to increase my xargs fu. I’ve been using pkill for solving what I think is a similar problem. pkill -f ‘python my_script.py’. I don’t know whether it would handle special switches…
Dave thanks for the comment. I didn’t know about pkill and pgrep. As for pkill matching special switches, I’m sure it could, because the man page says the matching pattern is an extended regular expression. pkill and pgrep look like they’re standard on Linux, Ubuntu at least. On my version of OS X, they’re only available from MacPorts in the proctools port.
For Unix triva geeks, the Linux man page says they were introduced in Sun’s Solaris 7.
Post a Comment