bash - timeout命令 - shell超时退出
使用超时重试Bash命令 (2)
重试功能来自:
http://fahdshariff.blogspot.com/2014/02/retrying-commands-in-shell-scripts.html
#!/bin/bash
# Retries a command on failure.
# $1 - the max number of attempts
# $2... - the command to run
retry() {
local -r -i max_attempts="$1"; shift
local -r cmd="[email protected]"
local -i attempt_num=1
until $cmd
do
if (( attempt_num == max_attempts ))
then
echo "Attempt $attempt_num failed and there are no more attempts left!"
return 1
else
echo "Attempt $attempt_num failed! Trying again in $attempt_num seconds..."
sleep $(( attempt_num++ ))
fi
done
}
# example usage:
retry 5 ls -ltr foo
如果你想在你的脚本中重试一个函数,你应该这样做:
# example usage:
foo()
{
#whatever you want do.
}
declare -fxr foo
retry 3 timeout 60 bash -ce 'foo'
如何重试bash命令直到其状态正常或达到超时?
我最好的镜头(我正在寻找更简单的东西):
NEXT_WAIT_TIME=0
COMMAND_STATUS=1
until [ $COMMAND_STATUS -eq 0 || $NEXT_WAIT_TIME -eq 4 ]; do
command
COMMAND_STATUS=$?
sleep $NEXT_WAIT_TIME
let NEXT_WAIT_TIME=NEXT_WAIT_TIME+1
done
您可以通过在测试中放置command
并稍微改变一点来简化一些事情。 否则脚本看起来很好:
NEXT_WAIT_TIME=0
until command || [ $NEXT_WAIT_TIME -eq 4 ]; do
sleep $(( NEXT_WAIT_TIME++ ))
done