如何将STDERR捕获到bash变量中而不影响STDOUT? [英] How can I capture STDERR into bash variable and not affect STDOUT?
问题描述
我正在尝试从 pg_dump
捕获错误,并且无法弄清楚如何将其放入bash变量中.这不起作用,因为STDOUT将要gzip.
I'm trying to capture the error from pg_dump
and cannot figure out how to get it into a bash variable. This does not work because STDOUT is going to gzip.
OUTPUT=$(/bin/pg_dump -c --if-exists --dbname=cfMaster -U cfMaster | /bin/gzip > ~cftvdun/dbbackups/cfMaster.tmp.sql.gz)
在这种情况下如何将STDERR放入bash变量中?
How can I get STDERR into a bash variable in this situation?
推荐答案
$()
构造始终捕获stdout,但是您可以在文件描述符之间进行切换.只需在 {}
中对管道进行分组,然后使用 2>& 1
将该组的stderr重定向到标准输出:
The $( )
construct always captures stdout, but you can juggle between file descriptors. Just group the pipeline in { }
, and then redirect the stderr of the group to standard output with 2>&1
:
output=$( { /bin/pg_dump -c --if-exists --dbname=cfMaster -U cfMaster | /bin/gzip > ~cftvdun/dbbackups/cfMaster.tmp.sql.gz; } 2>&1 )
如果您还想要标准输出(而不是仅将其发送到文件中),它将变得更加复杂.我认为在这种情况下,您将不得不通过FD#3进行调整.
If you also wanted the standard output (rather than just sending it to a file), it'd get more complicated. I think in that case you'd have to juggle through FD #3.
顺便说一句,我还建议使用小写(或大小写混合)的变量名,以免与外壳程序或其他实用程序具有特殊含义的变量发生意外冲突.
BTW, I'd also recommend using lowercase (or mixed-case) variable names to avoid accidental conflicts with the variables with special meaning to the shell or other utilities.
这篇关于如何将STDERR捕获到bash变量中而不影响STDOUT?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!