问题描述
我需要依赖于脚本中的几个单独的执行,并且不想将它们全部捆绑在一个丑陋的"if"语句中.我想使用退出代码"$?"每个执行并添加它;最后,如果该值超过阈值-我想执行一条命令.
I need to depend on few separate executions in a script and don't want to bundle them all in an ugly 'if' statement. I would like to take the exit code '$?' of each execution and add it; at the end, if this value is over a threshold - I would like to execute a command.
伪代码:
ALLOWEDERROR=5
run_something
RESULT=$?
..other things..
run_something_else
RESULT=$RESULT + $?
if [ $RESULT -gt ALLOWEDERROR ]
then echo "Too many errors"
fi
问题:即使互联网上有其他要求,bash也拒绝对待RESULT和$?作为整数.正确的语法是什么?
Issue: Even though the Internet claims otherwise, bash refuses to treat the RESULT and $? as integer. What is the correct syntax?
谢谢.
推荐答案
您可能想看一下内置的 trap
看看是否有帮助:
You might want to take a look at the trap
builtin to see if it would be helpful:
help trap
或
man bash
您可以为此类错误设置陷阱:
you can set a trap for errors like this:
#!/bin/bash
AllowedError=5
SomeErrorHandler () {
(( errcount++ )) # or (( errcount += $? ))
if (( errcount > $AllowedError ))
then
echo "Too many errors"
exit $errcount
fi
}
trap SomeErrorHandler ERR
for i in {1..6}
do
false
echo "Reached $i" # "Reached 6" is never printed
done
echo "completed" # this is never printed
如果您像这样计算错误(并且仅当它们是错误时),而不是使用" $?
",那么您不必担心返回值不是零或一.例如,单个返回值127会使您立即超过阈值.除了 ERR
,您还可以为其他信号注册 trap
.
If you count the errors (and only when they are errors) like this instead of using "$?
", then you don't have to worry about return values that are other than zero or one. A single return value of 127, for example, would throw you over your threshold immediately. You can also register trap
s for other signals in addition to ERR
.
这篇关于在bash中添加(收集)退出代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!