有时当我使用curl
命令将一些文件上传到我的ftp服务器执行bash脚本时,它会返回一些错误,例如:
56 response reading failed
Run Code Online (Sandbox Code Playgroud)
我必须找到错误的行并手动重新运行它们就可以了.
我想知道是否可以在发生错误时自动重新运行.
我的脚本是这样的:
#there are some files(A,B,C,D,E) in my to_upload directory,
# which I'm trying to upload to my ftp server with curl command
for files in `ls` ;
do curl -T $files ftp.myserver.com --user ID:pw ;
done
Run Code Online (Sandbox Code Playgroud)
但有时A,B,C会成功上传,只有D留下"错误56",所以我必须手动重新运行curl命令.此外,正如Will Bickford所说,我更喜欢不需要确认,因为我在脚本运行时总是睡着了.:)
phs*_*phs 41
这是我用来执行指数退避的bash片段:
# Retries a command a configurable number of times with backoff.
#
# The retry count is given by ATTEMPTS (default 5), the initial backoff
# timeout is given by TIMEOUT in seconds (default 1.)
#
# Successive backoffs double the timeout.
function with_backoff {
local max_attempts=${ATTEMPTS-5}
local timeout=${TIMEOUT-1}
local attempt=1
local exitCode=0
while (( $attempt < $max_attempts ))
do
if "$@"
then
return 0
else
exitCode=$?
fi
echo "Failure! Retrying in $timeout.." 1>&2
sleep $timeout
attempt=$(( attempt + 1 ))
timeout=$(( timeout * 2 ))
done
if [[ $exitCode != 0 ]]
then
echo "You've failed me for the last time! ($@)" 1>&2
fi
return $exitCode
}
Run Code Online (Sandbox Code Playgroud)
然后将它与任何正确设置失败退出代码的命令结合使用:
with_backoff curl 'http://monkeyfeathers.example.com/'
Run Code Online (Sandbox Code Playgroud)
也许这会有所帮助.它会尝试命令,如果失败,它会告诉你并暂停,让你有机会修复run-my-script
.
COMMAND=./run-my-script.sh
until $COMMAND; do
read -p "command failed, fix and hit enter to try again."
done
Run Code Online (Sandbox Code Playgroud)