bash - 从 bash 脚本中启动的命令中检索错误代码

标签 bash error-handling

好的,我对 bash 脚本编写 [高级的东西] 有点陌生,我需要一点帮助。我什至不知道如何准确表达这一点,所以我只会解释我在做什么以及我需要了解的内容。
在我的脚本中,我运行 ./configure 并且我需要能够捕获配置中是否存在错误并在 bash 脚本中做出相应的 react 。

代码是:

function dobuild {
echo -e "\e[1;35;40mExecuting Bootstrap and Configure\e[0m"
cd /devel/xbmc
if [ $Debug = "1" ];
then
#either outputs to screen or nulls output
./bootstrap >/dev/null
/usr/bin/auto-apt run ./configure --prefix=/usr --enable-gl --enable-vdpau --enable-crystalhd --enable-rtmp --enable-libbluray  >/dev/null
else
./bootstrap
/usr/bin/auto-apt run ./configure --prefix=/usr --enable-gl --enable-vdpau --enable-crystalhd --enable-rtmp --enable-libbluray
fi
}

并说配置返回错误 1 ​​或 2 我如何捕获并采取行动?

TIA

最佳答案

执行每个 shell 命令后,它的返回值是一个介于 0 和 255 之间的数字,可在 shell 变量 ? 中获得。 .您可以通过在它前面加上 $ 来获取该变量的值。运算符(operator)。

您必须小心 ? ,因为它被每个命令重置,甚至是测试 .例如:

some_command
if (( $? != 0 ))
then
   echo "Error detected! $?" >&2
fi

给:Error detected! 0因为?由测试条件复位。最好存储?如果您稍后要使用另一个变量,其中包括对其进行多次测试。

要在 bash 中进行数字测试,请使用 (( ... ))数字测试构造:
some_command
result=$?
if (( $result == 0 ))
then
   echo "it worked!"
elif (( $result == 1 ))
then
    echo "Error 1 detected!" >&2
elif (( $result == 2 ))
then
    echo "Error 2 detected!" >&2
else
    echo "Some other error was detected: $result" >&2
fi

或者使用 case陈述。

关于bash - 从 bash 脚本中启动的命令中检索错误代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15378789/

相关文章:

mysql - 从React表单发布到我的后端API时出错

haskell - Haskell中没有错误消息

bash - 如何在 IntelliJ 中设置 bash 解释器路径

bash - 使用 Bash 脚本轮换日志

Linux case 语句总是给出相同的结果

Bash 脚本,遍历文件夹中的文件失败

android - Android错误: ActivityThread.performLaunchActivity

android - 如何从Android WebView中的iframe捕获错误

error-handling - Julia 中抛出错误和返回错误的区别

linux - 两次之间每分钟执行一次 Cronjob