此问题已在此处有答案:
Capture stdout and stderr into different variables(21个回答)
2个月前关闭。
我试图捕获子命令的stderr,我的想法是这样的:
subErr(){
echo "${1}"
exit 1
}
BLOB=$(some long command || subErr $2)
aws configure set x_security_token_expires $(echo $BLOB|jq -r '.Credentials.Expiration') --profile DEFAULT
所以基本上,如果命令失败,将stderr提供给一个函数,该函数打印错误并退出。
如果命令成功,则将stdout分配给BLOB并继续处理
我如何才能做到这一点?
1条答案
按热度按时间9jyewag01#
如何将stderr保存到一个文件中,以便稍后由您的函数使用:
您可以使用
exec 2>"$errFile"
将所有stderr重定向到同一个文件,因此您不需要将其添加到每个命令调用中,但如果您希望为所有stderr输出添加idk,则需要添加idk。或者,请参阅redirect-stderr-and-stdout-to-different-variables-without-temporary-files,其中我特别喜欢:
你得按自己的需要按摩