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

我现在的做法是:

[~]$ 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>

当前回答

我使用gkill processname,其中gkill是以下脚本:

cnt=`ps aux|grep $1| grep -v "grep" -c`
if [ "$cnt" -gt 0 ]
then
    echo "Found $cnt processes - killing them"
    ps aux|grep $1| grep -v "grep"| awk '{print $2}'| xargs kill
else
    echo "No processes found"
fi

注意:它不会杀死命令行中有“grep”的进程。

其他回答

你可以用awk和backtics来做

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

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

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

试着用

ps aux | grep 'python csp_build.py' | head -1 | cut -d " " -f 2 | xargs kill

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

kill sigterm $(pgrep -i midori)

我的任务是杀死所有与regexp匹配的放在特定目录中的内容(在selenium测试之后,并不是所有内容都停止了)。这招对我很管用:

for i in `ps aux | egrep "firefox|chrome|selenium|opera"|grep "/home/dir1/dir2"|awk '{print $2}'|uniq`; do kill $i; done

在bash的一行中找到并杀死所有进程。

kill -9 $(ps -ef | grep '<exe_name>' | grep -v 'grep' | awk {'print $2'})

ps -ef | grep '<exe_name>' -给出匹配模式的运行进程详细信息(uname, pid等)的列表。输出列表还包括搜索它的grep命令。现在,对于kill,我们需要忽略这个grep命令过程。 ps -ef | grep' <exec_name>' | grep -v 'grep' -使用-v 'grep'添加另一个grep将删除当前的grep进程。 然后使用awk单独获取进程id。 然后将此命令保存在$(…)中,并将其传递给kill命令,以杀死所有进程。