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

我现在的做法是:

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

当前回答

根据https://stackoverflow.com/a/3510879/15603477的回答。小的优化。

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

使用tr -s ' '将多个空白(如果有的话)压缩为一个空白。

如果你遇到不允许的行动,请跟着>> https://unix.stackexchange.com/questions/89316/how-to-kill-a-process-that-says-operation-not-permitted-when-attempted

其他回答

这里有很多很好的答案-我使用了op接受的答案。只是添加了一个关于pkill和pgrep的小警告。正如你可能从他们的手册页看到的,在你的操作系统上,一些操作系统对进程名有15个字符的限制。-f选项绕过了我的操作系统,但我遇到了麻烦,直到我找到了这个选项!

如果pkill -f csp_build.py没有杀死进程,你可以添加-9来发送一个杀死信号,该信号不会被忽略。即pkill -9 -f csp_build.py

你只能使用pkill '^python*'来杀死正则表达式进程。

如果你想知道你要杀死什么或在杀死之前找到什么,只需使用pgrep -l '^python*',其中-l输出进程的名称。如果你不想用 Pkill,用just:

pgrep '^python*' |Xargs Kill

ps不需要用户开关。

kill `ps ax | grep 'python csp_build.py' | awk '{print $1}'`

我使用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”的进程。