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
How to write a shell script to find PID and Kill
提问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.sh
will 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.sh
in it. grep
will then pick up on its own process and the start.sh
one so you will get two PIDs back.
您创建了一个包含单词的子shell start.sh
。grep
然后将选择它自己的过程和start.sh
一个,这样你就会得到两个 PID。
This means when you are trying to kill both start.sh
and the
这意味着,当你试图杀死两个 start.sh
和
ps -eaf | grep "start.sh" | awk '{print }'
processes. The start.sh
will 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 pidof
rather 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
纯粹