发生错误时如何自动重新运行“curl”命令

有时当我用curl命令执行一个bash脚本来将一些file upload到我的ftp服务器时,它会返回一些错误,如:

 56 response reading failed 

我必须find错误的行并手动重新运行它们。

我想知道是否可以在错误发生时自动重新运行。


我的脚本是这样的:

 #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 

但是有时候A,B,C会被成功上传,只有D被留下了“错误56”,所以我不得不手动重新运行curl命令。 此外,正如威尔·比克福德所说,我更喜欢不需要确认,因为在脚本运行的时候,我总是睡着了。 🙂

Solutions Collecting From Web of "发生错误时如何自动重新运行“curl”命令"

这里是我用来执行指数后退的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=0 local exitCode=0 while (( $attempt < $max_attempts )) do set +e "$@" exitCode=$? set -e if [[ $exitCode == 0 ]] then break 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 } 

然后将其与任何正确设置失败退出代码的命令结合使用:

 with_backoff curl 'http://monkeyfeathers.example.com/' 

请注意,随着张贴with_backoff将设置bash的“死于错误” -e标志,你可能或可能不需要(我确实需要。)根据需要删除两个set行。

也许这会有所帮助。 它会尝试命令,如果失败,它会告诉你并暂停,给你一个修复run-my-script的机会。

 COMMAND=./run-my-script.sh until $COMMAND; do read -p "command failed, fix and hit enter to try again." done