diff --git a/home/bin/grkill b/home/bin/grkill new file mode 100755 index 0000000..e3a2c96 --- /dev/null +++ b/home/bin/grkill @@ -0,0 +1,48 @@ +#!/usr/bin/env python + +# grkill - Kill command and grep all in one! +# Usage: grkill [options] "grep string" +# +# Does a `ps aux | grep STRING` and for each PID found, runs a `kill` command +# passing any other options verbatim. For example, `grkill -9 application.py` +# would kill any process with "application.py" in its command line. +# +# --Kirsle +# http://sh.kirsle.net/ + +from sys import argv, exit +import re +import subprocess + +def main(): + if len(argv) < 2: + print "Usage: {} [options] ".format(argv[0]) + exit(1) + + # Separate the search string from other options. + options = argv[1:] + grep = options.pop() + + # Do a `ps aux | grep` + try: + ps = subprocess.check_output( + "ps aux | grep {} | grep -v grep | grep -v grkill".format(grep), + shell=True + ) + except: + print "No processes found." + exit(1) + + for line in ps.split("\n"): + if not line.strip(): + continue + pid = re.split(r'\s+', line)[1] + + # And kill it. + subprocess.call("kill {opts} {pid}".format( + opts=" ".join(options), + pid=pid, + ), shell=True) + +if __name__ == "__main__": + main()