如何在变量中存储标准误差 [英] How to store standard error in a variable
问题描述
假设我有一个如下所示的脚本:
Let's say I have a script like the following:
无用的.sh
echo "This Is Error" 1>&2
echo "This Is Output"
我还有另一个 shell 脚本:
And I have another shell script:
alsoUseless.sh
alsoUseless.sh
./useless.sh | sed 's/Output/Useless/'
我想将这是错误"或 useless.sh 中的任何其他 stderr 捕获到一个变量中.我们称之为错误.
I want to capture "This Is Error", or any other stderr from useless.sh, into a variable. Let's call it ERROR.
请注意,我将标准输出用于某些目的.我想继续使用 stdout,因此在这种情况下,将 stderr 重定向到 stdout 没有帮助.
Notice that I am using stdout for something. I want to continue using stdout, so redirecting stderr into stdout is not helpful, in this case.
所以,基本上,我想做
./useless.sh 2> $ERROR | ...
但这显然行不通.
我也知道我可以做到
./useless.sh 2> /tmp/Error
ERROR=`cat /tmp/Error`
但这既丑陋又不必要.
不幸的是,如果这里没有答案,那就是我将要做的.
Unfortunately, if no answers turn up here that's what I'm going to have to do.
我希望有另一种方式.
有人有更好的想法吗?
推荐答案
这样捕获错误文件会更简洁:
It would be neater to capture the error file thus:
ERROR=$(</tmp/Error)
shell 识别出这一点并且不必运行cat
"来获取数据.
The shell recognizes this and doesn't have to run 'cat
' to get the data.
更大的问题很难.我认为没有简单的方法可以做到这一点.您必须将整个管道构建到子 shell 中,最终将其最终标准输出发送到文件中,以便您可以将错误重定向到标准输出.
The bigger question is hard. I don't think there's an easy way to do it. You'd have to build the entire pipeline into the sub-shell, eventually sending its final standard output to a file, so that you can redirect the errors to standard output.
ERROR=$( { ./useless.sh | sed s/Output/Useless/ > outfile; } 2>&1 )
请注意,分号是必需的(在经典 shell 中 - Bourne、Korn - 当然;可能在 Bash 中也是如此).'{}
' 通过包含的命令执行 I/O 重定向.正如所写,它也会从 sed
中捕获错误.
Note that the semi-colon is needed (in classic shells - Bourne, Korn - for sure; probably in Bash too). The '{}
' does I/O redirection over the enclosed commands. As written, it would capture errors from sed
too.
警告:未经正式测试的代码 - 使用风险自负.
WARNING: Formally untested code - use at own risk.
这篇关于如何在变量中存储标准误差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!