shell BASH 4 -从子命令捕获错误消息[重复]

kcwpcxri  于 12个月前  发布在  Shell
关注(0)|答案(1)|浏览(107)

此问题已在此处有答案

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并继续处理
我如何才能做到这一点?

9jyewag0

9jyewag01#

如何将stderr保存到一个文件中,以便稍后由您的函数使用:

errFile=$(mktemp) || exit
trap 'rm -f "$errFile"; exit' 0

subErr(){
  cat "$errFile"
  exit 1
}

BLOB=$(some long command 2>"$errFile") || subErr

您可以使用exec 2>"$errFile"将所有stderr重定向到同一个文件,因此您不需要将其添加到每个命令调用中,但如果您希望为所有stderr输出添加idk,则需要添加idk。
或者,请参阅redirect-stderr-and-stdout-to-different-variables-without-temporary-files,其中我特别喜欢:

{
  IFS= read -rd '' err
  IFS= read -rd '' out
  IFS= read -rd '' status
} < <({ out=$(ls /dev/null /x); } 2>&1; printf '\0%s' "$out" "$?")

你得按自己的需要按摩

相关问题