&1)" echo $response 如果 B-6ren">
gpt4 book ai didi

bash - 在 bash 脚本中使用 `set -e` 命令失败后继续

转载 作者:行者123 更新时间:2023-11-29 09:27:47 25 4
gpt4 key购买 nike

我正在编写一个脚本来解析 Bundler 的错误输出,但我遇到了一个我不确定如何处理的问题:

response="$(bundle install 2>&1)"
echo $response

如果 Bundler 失败,那么 $response 就是空白,我无法按需解析它。我试过:

response="$(bundle install 2>&1 || true)"
echo $response

这行得通,但不是我想要的,因为我仍然希望我的脚本在 Bundler 失败时失败。

如何让 bundle install 失败并仍然读取其输出?

我还应该补充一点,我正在使用我需要的 set -e

编辑:

阅读 PSkocik 的回答后,这让我可以继续解决错误,同时在错误发生时仍然退出:

response="$(bundle install 2>&1)" || bundle_status=$?
# Continue working (In my case, I'm parsing the errors to give more
# meaningful output for the context in which bundler is being run).
# And now I can exit with the given status code, or default to 0.
exit ${bundle_status:-0}

最佳答案

这是因为 -e 选项。您需要确保错误返回状态得到测试:

man sh on -e(man bash 在这方面有点冗长,但在同样的精神)

If not interactive, exit immediately if any untested command fails. The exit status of a command is considered to be explicitly tested if the command is used to control an if, elif, while, or until; or if the command is the left hand operand of an “&&” or “||” operator.

这是一个带有打包器模拟的示例(在 sh 中,但也应该在 bash 中工作):

#!/bin/sh
set -e
bundle(){
echo "i'm errorring here" >&2
return 32
}

response="$(bundle 2>&1)"
echo "won't get here if -e is set"

你可以这样解决:

response="$(bundle 2>&1)" || ret=$? #`set -e` won't kill us now
echo "will get here now"
echo "the bundle command exited with $ret"
echo "the response is ${response}"

如果您需要回显不属于您的字符串,您应该考虑使用 printf 而不是 echo(并且不要忘记双引号):https://unix.stackexchange.com/questions/65803/why-is-printf-better-than-echo

关于bash - 在 bash 脚本中使用 `set -e` 命令失败后继续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32563332/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com