从bash脚本中启动的命令检索错误代码
问题描述:
好吧,我对bash脚本[高级内容]很陌生,我需要一些帮助。我甚至不知道如何解释这个问题,所以我只会解释我正在做什么以及我需要了解的内容。 在我的脚本中运行./configure,我需要能够捕获配置中是否有错误,并在bash脚本中作出相应反应。从bash脚本中启动的命令检索错误代码
代码:
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变量$?中。所以,你必须匹配成功和失败
if [ $? == 1 ]
then
#do something
else
#do something else
fi
答
的返回值,每一shell命令它的返回值,0和255之间的数字执行后,在shell变量?
可用。您可以通过在$
运算符前加前缀来获取此变量的值。
你必须小心谨慎?
,因为它被每个命令重置,即甚至测试。例如:
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
声明。
答
其他答案约$?是很好的(虽然要小心假设值不是0而不是0),或者不同版本的同一个命令可能会因不同的值而失败),但是如果您只需立即采取行动成功或失败,则可以简化事情:
if command ; then
# success code here
else
# failure code here
fi
或者,如果你只是想采取行动的失败,这里的老年人弹一劈(结肠是空的命令,但它符合当时的条款):
if command ; then :
else
# failure code here
fi
但在现代贝壳这样比较好:
if ! command ; then # use the ! (not) operator
# failure code here
fi
而且,如果你只需要做简单的事情,你可以使用“短路”运算符:
command1 && command2_if_command1_succeeds
command1 || command2_if_command1_fails
单命令那些只工作,串起更多& &和||在他们身上不会做你在大多数情况下可能会想到的,所以大多数人都会避免这种情况但是,你可以做多个命令,如果你将它们分组:
command1 && { command2; command3; command4; }
,可以得到难以阅读,因此最好保持它的简单,如果你使用它:
command1 || { echo "Error, command1 failed!" >&2; exit 1; }
我刚刚发现确切字符串谷歌搜索。所以如果我做了一个./configure,它运行并以1的错误结束,那么这将允许我做正确的事情?如果它有2的错误,我可以elif [$ 1 == 2]? – user1567394 2013-03-13 07:01:11
正确..除了在你的脚本中,返回值是由'/ usr/bin/auto-apt'返回的事实。 – uba 2013-03-13 07:02:37
感谢您的回复,但我不完全确定您的意思。 – user1567394 2013-03-13 07:05:25