我经常需要在编程期间终止一个进程。

我现在的做法是:

[~]$ ps aux | grep 'python csp_build.py'
user    5124  1.0  0.3 214588 13852 pts/4    Sl+  11:19   0:00 python csp_build.py
user    5373  0.0  0.0   8096   960 pts/6    S+   11:20   0:00 grep python csp_build.py
[~]$ kill 5124

如何自动提取进程id并在同一行中杀死它?

是这样的:

[~]$ ps aux | grep 'python csp_build.py' | kill <regex that returns the pid>

当前回答

通过关键字midori终止进程,例如:

kill sigterm $(pgrep -i midori)

其他回答

一个只使用awk(和ps)的方法:

ps aux | awk '$11" "$12 == "python csp_build.py" { system("kill " $2) }'

通过使用字符串相等性测试,我防止匹配这个过程本身。

ps -o uid,pid,cmd|awk '{if($1=="username" && $3=="your command") print $2}'|xargs kill -15

你可以用awk和backtics来做

ps auxf |grep 'python csp_build.py'|`awk '{ print "kill " $2 }'`

awk中的$2打印列2,backtics运行打印的语句。

但是一个更干净的解决方案是让python进程将它的进程id存储在/var/run中,然后你可以简单地读取该文件并杀死它。

如果你有pkill,

pkill -f csp_build.py

如果您只想根据进程名(而不是完整的参数列表)进行grep,则取消-f。

我用这个来杀死Firefox当它被脚本抨击和cpu抨击:) 把“Firefox”换成你想要的应用。我在Bash shell - OS X 10.9.3达尔文。

kill -Hup $(ps ux | grep Firefox | awk 'NR == 1 {next} {print $2}' | uniq | sort)