如何在变量中存储标准错误 [英] How to store standard error in a variable
问题描述
假设我有一个如下脚本:
Let's say I have a script like the following:
useless.sh
useless.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中捕获"This Is Error"或任何其他stderr到一个变量中. 我们称它为错误.
I want to capture "This Is Error", or any other stderr from useless.sh, into a variable. Let's call it ERROR.
请注意,我正在使用stdout进行操作.我想继续使用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.
我希望还有另一种方式.
I'm hoping there's another way.
有人有更好的主意吗?
推荐答案
这样捕获错误文件会更整洁:
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.
更大的问题很难解决.我认为没有简单的方法可以做到这一点.您必须将整个管道构建到子外壳中,最终将其最终标准输出发送到文件中,以便可以将错误重定向到标准输出.
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屋!