1
0
.dotfiles/home/bin/grkill

49 lines
1.2 KiB
Python
Executable File

#!/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] <grep string>".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()