gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 08:08:06 25 4
gpt4 key购买 nike

好的,我对 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/

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