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

我现在的做法是:

[~]$ 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”的进程。

其他回答

如果你有pkill,

pkill -f csp_build.py

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

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

这将只返回pid

pgrep -f 'process_name'

因此要在一行中终止任何进程:

kill -9 $(pgrep -f 'process_name')

或者,如果你知道这个过程的确切名称,你也可以试试pidof:

kill -9 $(pidof 'process_name')

但是,如果您不知道进程的确切名称,那么使用pgrep会更好。

如果有多个进程使用相同的名称运行,并且你想杀死第一个进程,那么:

kill -9 $(pgrep -f 'process_name' | head -1)

还要注意的是,如果你担心大小写敏感,那么你可以像在grep中一样添加-i选项。例如:

kill -9 $(pgrep -fi chrome)

更多关于信号和pgrep的信息在man 7信号或man信号和man pgrep

一个衬套:

Ps aux | grep -i csp_build | awk '{print $2}' | xargs sudo kill -9

打印列2:awk '{Print $2}' Sudo是可选的 运行kill -9 5124, kill -9 5373等(kill -15更优雅,但稍慢)


奖金:

我还在.bash_profile中定义了2个快捷函数 (~ /。Bash_profile是用于osx的,你必须看看什么适用于你的*nix机器)。

p关键字 列出所有包含关键字的进程 用法例如:p csp_build, p python等

bash_profile代码:

# FIND PROCESS
function p(){
        ps aux | grep -i $1 | grep -v grep
}

ka关键字 杀死所有具有此关键字的进程 用法例如:ka csp_build, ka python等 可选的kill级别,例如:ka csp_build 15, ka python 9

bash_profile代码:

# KILL ALL
function ka(){

    cnt=$( p $1 | wc -l)  # total count of processes found
    klevel=${2:-15}       # kill level, defaults to 15 if argument 2 is empty

    echo -e "\nSearching for '$1' -- Found" $cnt "Running Processes .. "
    p $1

    echo -e '\nTerminating' $cnt 'processes .. '

    ps aux  |  grep -i $1 |  grep -v grep   | awk '{print $2}' | xargs sudo kill -klevel
    echo -e "Done!\n"

    echo "Running search again:"
    p "$1"
    echo -e "\n"
}

对于基本bash版本

Kill $(pidof <my_process>)