bash 如何编写一个shell脚本来查找PID并杀死

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30514923/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 13:04:04  来源:igfitidea点击:

How to write a shell script to find PID and Kill

linuxbashshellunix

提问by MPNation

I am trying to write a script that looks for the PID of another script that ran previously. Once it finds that PID it then sends a kill signal.

我正在尝试编写一个脚本来查找以前运行的另一个脚本的 PID。一旦找到该PID,它就会发送一个终止信号。

I can find the PID but the kill signal does not process, I get a return message that it is not a PID.

我可以找到 PID 但终止信号没有处理,我收到一条返回消息,表明它不是 PID。

Here is what I am doing:

这是我在做什么:

#!/bin/bash   
 PID=`ps -eaf | grep "start.sh" | awk '{print }'`
    echo "$PID"    
    if [[ -z "$PID" ]];
     then(
            echo "Start script is not running!"
    )else(
            kill -9 $PID
    )fi

The script it is trying to kill starts many other scripts so I am hoping that killing start.shwill kill all child processes.

它试图杀死的脚本启动了许多其他脚本,所以我希望杀死start.sh会杀死所有子进程。

采纳答案by Songy

When you run

当你跑

ps -eaf | grep "start.sh" | awk '{print }'

you create a subshell with the word start.shin it. grepwill then pick up on its own process and the start.shone so you will get two PIDs back.

您创建了一个包含单词的子shell start.shgrep然后将选择它自己的过程和start.sh一个,这样你就会得到两个 PID。

This means when you are trying to kill both start.shand the

这意味着,当你试图杀死两个 start.sh

ps -eaf | grep "start.sh" | awk '{print }'

processes. The start.shwill die but the other will no longer exist so can't be killed, so it gives you an error.

过程。该start.sh会死,但对方将不再存在,因此不能被杀死,所以它给你一个错误。

If you were to split up the commands you might have better luck:

如果您要拆分命令,您的运气可能会更好:

PIDS=$(ps -eaf)
PID=$(echo "$PIDS" | grep "start.sh" | awk '{print }')

回答by Alex

Try using pgrep:

尝试使用pgrep

PID=$(pgrep yourprocesname)

回答by Trevor Hickey

Here is another solution that may be useful for someone:

这是另一个可能对某人有用的解决方案:

#!/bin/bash  
kill-process-by-name(){  
   processes=$(ps -A)
   kill -9 `echo "$processes" | grep "" | cut -f2 -d" "`
}

kill-process-by-name "start.sh"

回答by jag

You could use pidofrather then ps -ef

你可以使用pidof而不是ps -ef

PID=`pidof start.sh | awk '{print }'`
echo "$PID csshst will be stopped"
if [[ -z "$PID" ]]; then
(
        kill -9 $PID
)
fi

回答by user12748121

trashPID=`pidof start.sh | awk '{print }'`
echo "$PID csshst will be stopped"
if [[ -z "$PID" ]]; then
(
        kill -9 $PID
)
fi

purely

纯粹