如何在 bash 脚本中静默使用 unix kill 命令?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9402361/
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 01:37:51  来源:igfitidea点击:

How can you use the unix kill command silently in a bash script?

linuxbash

提问by Jimmy

I'm trying to check if a particular process is running, and if it is, try and kill it.

我正在尝试检查特定进程是否正在运行,如果是,请尝试将其杀死。

I've come up with the following so far:

到目前为止,我提出了以下几点:

PID=$(ps aux | grep myprocessname | grep -v grep | awk '{print }')

if [ -z $PID];
then    
    echo Still running on PID $PID, attempting to kill..
    kill -9 $PID > /dev/null
fi

However when I run this, I get the following output:

但是,当我运行它时,我得到以下输出:

kill: usage: kill [-s sigspec | -n signum | -sigspec] pid | jobspec ... or kill -l [sigspec]

What is the best way to kill a running process on unix silently?

静默杀死 unix 上正在运行的进程的最佳方法是什么?

回答by Mat

[ -z $PID]

is true if $PIDis empty, not the other way around, so your test is inverted.

如果$PID为空,则为真,而不是相反,因此您的测试被反转。

You should be using pgrepif you have that on your system too. (Or even better: pkilland stop worrying about all that shell logic.)

pgrep如果您的系统上也有它,您应该使用它。(或者甚至更好:pkill不要担心所有这些 shell 逻辑。)

回答by John

The answer is easier
The program "killall" is part of almost any distribution.

答案更简单
程序“killall”几乎是任何发行版的一部分。

Examples:

例子:

killall name_of_process &> /dev/null
killall -9 name_of_process &> /dev/null
(( $? == 0)) && echo "kill successful";

Now there also is "pkill" and "pgrep" Example:

现在还有“pkill”和“pgrep”示例:

pkill -9 bash &> /dev/null
(( $? == 0)) && echo "kill successful";

Example:

例子:

for pid in $(pgrep bash); do
 kill -9 $pid &> /dev/null
 (( $? == 0)) && echo "kill of $pid successful" || echo "kill of $pid failed";
done

And last as you used "ps" in your example, here a better way to use it without the requirement of "grep" "grep -v" and "awk":

最后,当您在示例中使用“ps”时,这里有一种更好的使用方法,无需“grep”、“grep -v”和“awk”:

PIDS="$(ps -a -C myprocessname -o pid= )"
while read pid; do 
  kill -9 $pid &> /dev/null
  ((!$?)) && echo -n "killed $pid,"; 
done <<< "$p"

All those listed methods are better than the long pipe-pipe-pipe imho

所有列出的方法都比长管 - 管 - 管 imho 好

回答by Lars Kotthoff

Try if [ X$PID != X ]in your condition. This is the usual idiom for checking whether a string is empty.

if [ X$PID != X ]在你的情况下尝试。这是检查字符串是否为空的常用习惯用法。