bash 变量分别捕获 stderr 和 stdout 或获取退出值

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

bash variable capture stderr and stdout separately or get exit value

bashvariablesstdoutcapturestderr

提问by mhost

I need to capture the output and error of a command in my bash script and know whether the command succeeded or not.

我需要在我的 bash 脚本中捕获命令的输出和错误,并知道该命令是否成功。

At the moment, I am capturing both like this:

目前,我正在像这样捕获两者:

output=$(mycommand 2>&1)

I then need to check the exit value of mycommand. If it failed, I need to do some stuff with the output, if the command succeeded, I don't need to touch the output.

然后我需要检查 mycommand 的退出值。如果失败,我需要对输出做一些事情,如果命令成功,我不需要触摸输出。

Since I am capturing the output, checking $? is always a 0 since bash succeeded at capturing the output into the variable.

由于我正在捕获输出,因此检查 $? 始终为 0,因为 bash 成功地将输出捕获到变量中。

This is a very time sensitive script, so we are trying to avoid any slower solutions like outputting to a file and re-reading it in.

这是一个对时间非常敏感的脚本,因此我们试图避免任何较慢的解决方案,例如输出到文件并重新读取它。

If I could capture stdout to one variable and stderr to another, that would solve my problem because I could just check if the error variable was empty or not.

如果我可以将 stdout 捕获到一个变量并将 stderr 捕获到另一个变量,那将解决我的问题,因为我可以只检查错误变量是否为空。

Thanks.

谢谢。

采纳答案by paxdiablo

What version of bashare you using? The capture of the output has zeroeffect on the return code with my version, 4.1.5:

bash你用的是什么版本?输出的捕获对我的版本的返回码的影响为零4.1.5

pax> false; echo $?
1
pax> echo $?
0
pax> x=$(false 2>&1) ; echo $?
1

It's not always a good idea to rely on standard error being non-empty to detect errors. Many programs don't output errors but rely solelyon the return code.

依靠非空的标准错误来检测错误并不总是一个好主意。许多程序不输出错误,而依赖于返回码。

回答by phs

The problem only seems to manifest when the output is captured to a localvariable within a function:

该问题似乎仅在将输出捕获到函数内的局部变量时才会出现:

$ echo $BASH_VERSION
3.2.48(1)-release
$ false; echo $?
1
$ echo $?
0
$ x=$(false 2>&1) ; echo $?
1
$ function f {
> local x=$(false 2>&1) ; echo $?
> }
$ f
0
$ function g {
> x=$(false 2>&1) ; echo $?
> }
$ g
1

Notice that only function f, which captures x to a local, can express the behavior. Particularly, function g which does the same thing, but without the 'local' keyword, works.

请注意,只有将 x 捕获到本地的函数 f 才能表达行为。特别是,执行相同操作但没有 'local' 关键字的函数 g 可以工作。

One can therefore not use a local variable, and perhaps 'unset' it after use.

因此,不能使用局部变量,并且可能在使用后“取消设置”它。

EDITNVRAM points out that the local declaration can be made beforehand to avoid the issue:

EDITNVRAM 指出可以预先进行本地声明以避免该问题:

$ function h {
>   local x
>   x=$(false 2>&1) ; echo $?
> }
$ h
1