bash 如何屏蔽kill输出
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8074904/
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 shield the kill output
提问by chemila
I run a script like:
我运行一个脚本,如:
sleep 20 &
PID=$!
kill -9 $PID >/dev/null 2>&1
I dont want the script show the output like:
我不希望脚本显示如下输出:
line 51: 22943 Killed sleep
I have no idea why this happen, I have redirect the output to /dev/null
我不知道为什么会发生这种情况,我已将输出重定向到 /dev/null
回答by Gordon Davisson
The message isn't coming from either killor the background command, it's coming from bash when it discovers that one of its background jobs has been killed. To avoid the message, use disownto remove it from bash's job control:
该消息既不是来自kill后台命令也不是来自后台命令,而是来自 bash 当它发现其后台作业之一已被终止时。为避免该消息,请使用disown将其从 bash 的作业控制中删除:
sleep 20 &
PID=$!
disown $PID
kill -9 $PID
回答by Roel Van de Paar
This can be done using 'wait' + redirection of wait to /dev/null :
这可以使用“等待”+将等待重定向到 /dev/null 来完成:
sleep 2 &
PID=$!
kill -9 $PID
wait $PID 2>/dev/null
sleep 2
sleep 2
sleep 2
This script will not give the "killed" message:
这个脚本不会给出“被杀死”的消息:
-bash-4.1$ ./test
-bash-4.1$
While, if you try to use something like:
同时,如果您尝试使用以下内容:
sleep 2 &
PID=$!
kill -9 $PID 2>/dev/null
sleep 2
sleep 2
sleep 2
It will output the message:
它将输出消息:
-bash-4.1$ ./test
./test: line 4: 5520 Killed sleep 2
-bash-4.1$
I like this solution much more than using 'disown' which may have other implications.
我更喜欢这个解决方案,而不是使用可能有其他含义的“disown”。
Idea source: https://stackoverflow.com/a/5722850/1208218
回答by phily
Another way to disable job notifications is to put your command to be backgrounded in a sh -c 'cmd &'construct.
禁用作业通知的另一种方法是将您的命令置于sh -c 'cmd &'构造中。
#!/bin/bash
# ...
sh -c '
sleep 20 &
PID=$!
kill -9 $PID # >/dev/null 2>&1
'
# ...
回答by Joey Cote
I was able to accomplish this by redirecting the output of the command that I am running in the background. In your case it would look like:
我能够通过重定向我在后台运行的命令的输出来实现这一点。在您的情况下,它看起来像:
sleep 20 >>${LOG_FILE} 2>&1 &
... or if you do not want a log file:
...或者如果您不想要日志文件:
sleep 20 &> /dev/null &
Then, when you want to kill that background process' PID, it will not show on standard out.
然后,当您想终止该后台进程的 PID 时,它不会显示在标准输出上。

