如何存储标准误差的变量在Bash脚本 [英] How to store standard error in a variable in a Bash script
问题描述
让我们说我有类似下面的脚本:
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任何其他错误,都到一个变量。
让我们把它错误。
I want to capture "This Is Error", or any other stderr from useless.sh, into a variable. Let's call it ERROR.
请注意,我用的标准输出的东西。我想继续使用标准输出,这样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.
所以,基本上,我想要做的。
So, basically, I want to do
./useless.sh 2> $ERROR | ...
但显然行不通。
我也知道,我可以做
./useless.sh 2> /tmp/Error
ERROR=`cat /tmp/Error`
但是这是丑陋的和不必要的。
but that's ugly and unnecessary.
不幸的是,如果没有答案打开了这里,这就是我将要做的。
Unfortunately, if no answers turn up here that's what I'm going to have to do.
我希望有另一种方式。
任何人有任何更好的想法?
Anyone have any better ideas?
推荐答案
这将是整洁捕捉到错误文件这样的:
It would be neater to capture the error file thus:
ERROR=$(</tmp/Error)
外壳认识到这一点,并没有运行猫
'来获取数据。
更大的问题是很难的。我不认为有一个简单的方法来做到这一点。你必须建立整个管道进入子壳,最终发送其最终的标准输出到一个文件中,这样就可以将错误重定向到标准输出。
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 )
请注意,需要分号(经典贝壳 - 伯恩,科恩 - 肯定的,可能是在击太)。在 {}
执行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.
(未经测试的正式code - 使用在自己的风险)
(Formally untested code - use at own risk.)
这篇关于如何存储标准误差的变量在Bash脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!