我需要执行一个命令并检查它是否成功。如果出现错误,我应该再试一次,并且以下代码按预期工作。
但是如果我需要尝试相同的命令 3 或 4 次才能成功执行怎么办? if / else 子句将变得非常复杂。
some command
if [ $? -eq 0 ];then
echo "success"
else
echo "failed first attempt trying again"
some command
if [ $? -eq 0 ];then
echo "success in second attempt"
else
echo "failed second attempt"
fi
fi
有没有更好的方法来编写一个脚本,在退出之前尝试该命令四次?
答案1
使用循环执行 /usr/local/some/command 的次数由 MAX_TRIES 决定。如果所有执行尝试均未成功,则会出错并显示代码 $ERR。如果成功,则会立即退出 0 并跳出循环。
#!/bin/bash
ERR=1 # or some non zero error number you want
MAX_TRIES=4
COUNT=0
while [ $COUNT -lt $MAX_TRIES ]; do
/usr/local/some/command
if [ $? -eq 0 ];then
exit 0
fi
let COUNT=COUNT+1
done
echo "Too many non-successful tries"
exit $ERR
如果你愿意,你可以使用 ac 风格的循环
#!/bin/bash
ERR=1 # or some non zero error number you want
MAX_TRIES=4
for (( i=1; i<=$MAX_TRIES; i++ ))
do
/usr/local/some/command
if [ $? -eq 0 ];then
exit 0
fi
done
echo "Too many non-sucessful tries"
exit $ERR
答案2
我真的很奇怪你怎么不知道关于 while 循环。
编辑。按照友好版主的要求,插入,重大的 狂欢蛋糕。耶,蛋糕!
while [ $w_count -lt $w_maxtries ]; do
some command
if [ $? -ne 0 ]; then
# cmd failed
let w_count=w_count+1
# optional, consider redirecting to STDERR.
echo "Warning, command failed the ${w_count}th time!"
if [[ $w_count -ge $(( $w_maxtries - 1 )) ]]; then
# whoops too many tries
echo "Giving up"
exit 1
fi
else
# Yay it worked
break
fi
done
# continue here.