在 bash 脚本中临时重定向 stderr

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

Temporary redirection of stderr in a bash script

bashsegmentation-faultredirectstdinstderr

提问by Karl Yngve Lerv?g

I have a simple script which is used to start another program. This other program may sometimes yield a SIGSEGV, which disrupts my output. I have therefore added a couple of lines which is supposed to temporarily redirect the stderrto /dev/nullsuch that the SIGSEGVis ignored. The following is a draft of my code:

我有一个简单的脚本,用于启动另一个程序。这个其他程序有时可能会产生一个SIGSEGV,这会破坏我的输出。因此,我增加了几个这是应该暂时重定向线stderr,以/dev/null使得SIGSEGV被忽略。以下是我的代码草稿:

exec 2> /dev/null
progname >& ./tmp/run.txt && run_status='OK'
exec 2>1

The problem is that the last line does not do what I want. The first line obviously works, and redirects the stderr. The last line is supposed to return the stderrback to where it was before (which I have only supposed is the same as stdout).

问题是最后一行没有做我想要的。第一行显然有效,并将stderr. 最后一行应该返回stderr到它之前的位置(我只假设它与 相同stdout)。

Any help would be appriciated!

任何帮助都会受到赞赏!

回答by Magnus Hiie

Another option is:

另一种选择是:

exec 3> /dev/stderr 2> /dev/null
progname >& ./tmp/run.txt && run_status='OK'
exec 2>&3

Or even

甚至

exec 3>&2 2> /dev/null
progname >& ./tmp/run.txt && run_status='OK'
exec 2>&3

That way the script preserves the separation of stdout and stderr for the script (ie. the scripts stdout and stderr can be redirected separately.

这样脚本就保留了脚本的 stdout 和 stderr 的分离(即脚本 stdout 和 stderr 可以单独重定向。

回答by Paul Tomblin

Why not just redirect it for the progname run only?

为什么不只针对 progname 运行重定向它?

   progname > ./tmp/run.txt 2>/dev/null && run_status='OK'

Or possibly

或者可能

{
   progname > ./tmp/run.txt && run_status='OK'
} 2>/dev/null