bash变量分别捕获stderr和stdout或获取退出值
我需要捕获 bash 脚本中命令的输出和错误,并知道该命令是否成功。
目前,我正在像这样捕获两者:
output=$(mycommand 2>&1)
然后我需要检查 mycommand 的退出值。如果失败,我需要对输出做一些事情,如果命令成功,我不需要触摸输出。
由于我正在捕获输出,因此检查 $?始终为 0,因为 bash 成功将输出捕获到变量中。
这是一个对时间非常敏感的脚本,因此我们试图避免任何较慢的解决方案,例如输出到文件并重新读入。
如果我可以将 stdout 捕获到一个变量并将 stderr 捕获到另一个变量,那将解决我的问题,因为我可以只需检查错误变量是否为空。
谢谢。
I need to capture the output and error of a command in my bash script and know whether the command succeeded or not.
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.
Since I am capturing the output, checking $? is always a 0 since bash succeeded at capturing the output into the variable.
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.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您使用的
bash
版本是什么?对于我的版本4.1.5
,输出的捕获对返回代码的影响零:依靠非空标准错误来执行错误并不总是一个好主意。检测错误。许多程序不输出错误,而是仅依赖返回代码。
What version of
bash
are you using? The capture of the output has zero effect on the return code with my version,4.1.5
: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 solely on the return code.
仅当输出被捕获到函数内的本地变量时,问题似乎才显现出来:
请注意,只有将 x 捕获到本地的函数 f 才能表达该行为。特别是,函数 g 可以做同样的事情,但没有 'local' 关键字。
因此,不能使用局部变量,并且可能在使用后“取消设置”它。
编辑 NVRAM指出可以提前进行本地声明以避免该问题:
The problem only seems to manifest when the output is captured to a local variable within a function:
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.
One can therefore not use a local variable, and perhaps 'unset' it after use.
EDIT NVRAM points out that the local declaration can be made beforehand to avoid the issue: