bash bash中的条件重定向
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8756535/
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
conditional redirection in bash
提问by daniel kullmann
I have a bash script that I want to be quiet when run without attached tty (like from cron). I now was looking for a way to conditionally redirect output to /dev/null in a single line. This is an example of what I had in mind, but I will have many more commands that do output in the script
我有一个 bash 脚本,我想在没有附加 tty 的情况下运行时保持安静(例如来自 cron)。我现在正在寻找一种在一行中有条件地将输出重定向到 /dev/null 的方法。这是我想到的一个例子,但我会有更多的命令在脚本中输出
#!/bin/bash
# conditional-redirect.sh
if tty -s; then
REDIRECT=
else
REDIRECT=">& /dev/null"
fi
echo "is this visible?" $REDIRECT
Unfortunately, this does not work:
不幸的是,这不起作用:
$ ./conditional-redirect.sh
is this visible?
$ echo "" | ./conditional-redirect.sh
is this visible? >& /dev/null
what I don't want to do is duplicate all commands in a with-redirection or with-no-redirection variant:
我不想做的是复制带重定向或不带重定向变体中的所有命令:
if tty -s; then
echo "is this visible?"
else
echo "is this visible?" >& /dev/null
fi
EDIT:
编辑:
It would be great if the solution would provide me a way to output something in "quiet" mode, e.g. when something is really wrong, I might want to get a notice from cron.
如果该解决方案能为我提供一种以“安静”模式输出某些内容的方法,那就太好了,例如,当某些事情真的出错时,我可能想从 cron 收到通知。
回答by paxdiablo
For bash, you can use the line:
对于bash,您可以使用以下行:
exec &>/dev/null
This will direct allstdoutand stderrto /dev/nullfrom that point on. It uses the non-argument version of exec.
这将直接所有stdout,并stderr以/dev/null从该点。它使用exec.
Normally, something like exec xyzzywould replace the program in the current process with a new program but you can use this non-argument version to simply modify redirections while keeping the current program.
通常,类似的事情exec xyzzy会用新程序替换当前进程中的程序,但您可以使用此无参数版本来简单地修改重定向,同时保留当前程序。
So, in your specific case, you could use something like:
因此,在您的特定情况下,您可以使用以下内容:
tty -s
if [[ $? -eq 1 ]] ; then
exec &>/dev/null
fi
If you want the majority of output to be discarded but still want to output some stuff, you can create a new file handle to do that. Something like:
如果您希望丢弃大部分输出但仍想输出一些内容,您可以创建一个新的文件句柄来做到这一点。就像是:
tty -s
if [[ $? -eq 1 ]] ; then
exec 3>&1 &>/dev/null
else
exec 3>&1
fi
echo Normal # won't see this.
echo Failure >&3 # will see this.
回答by daniel kullmann
回答by Codoscope
You can use a function:
您可以使用一个函数:
function the_code {
echo "is this visible?"
# as many code lines as you want
}
if tty -s; then # or other condition
the_code
else
the_code >& /dev/null
fi

