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

eri*_*cal 16 linux bash curl

有时当我使用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)

  • @ user1076599刚开始,你可以将它粘贴到靠近顶部的脚本中,然后删除`set + e`和`set -e`行.然后,您就可以在脚本中使用它了.为了获得更好的功能,您可以将它放在shell的登录脚本(`〜/ .profile`,`〜/ .bash_profile`或`〜/ .bashrc`)中. (2认同)
  • "while [[$ attempt <$ max_attempts]]"将导致程序过早退出,因为这实际上是在进行字符串比较而不是比较整数.如果max_attempts设置为大于9,它将始终失败.解决方案是使用"while(($ attempt <$ max_attempts))"而不是. (2认同)
  • 使用 `attempt=1` 精确执行由 `$ATTEMPTS` 定义的尝试次数。使用 `attempts=0` 它会额外做一个。见 https://gist.github.com/fernandoacorreia/b4fa9ae88c67fa6759d271b743e96063 (2认同)

Kev*_*vin 6

也许这会有所帮助.它会尝试命令,如果失败,它会告诉你并暂停,让你有机会修复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)