Bash while 循环在成功的 curl 请求后停止

hey*_*eya 8 scripting bash shell-script

我目前正在学习如何编写 bash 脚本。一旦我的 curl 请求收到 200 响应代码,如何停止 while 循环?

aws --endpoint-url http://s3.sample.com/ s3 cp hello.php s3://bucket/
while [ true ]
do
    curl http://sample.com/hello.php &> /dev/null
done
Run Code Online (Sandbox Code Playgroud)

fra*_*san 23

对建议的重复目标的接受答案显示了如何curl在任何服务器错误上失败,并返回22其退出状态。基于此,你可以写:

until curl -s -f -o /dev/null "http://example.com/foo.html"
do
  sleep 5
done
Run Code Online (Sandbox Code Playgroud)

其中显示“直到curl成功完成请求的传输,等待 5 秒并重试”。-f使curl服务器错误失败,-s阻止它打印消息和进度表,-o /dev/null假设您对响应的内容不感兴趣。

但是,curl能够自行重试,不需要 shell 循环。例如,要使其重试十次并在重试前休眠五秒钟:

curl --retry 10 --retry-delay 5 -s -o /dev/null "http://example.com/foo.html"
Run Code Online (Sandbox Code Playgroud)

或者,如果您希望它即使在出现非暂时性 HTTP 错误(例如 404)时也重试:

curl --retry 10 -f --retry-all-errors --retry-delay 5 \
  -s -o /dev/null "http://example.com/foo.html"
Run Code Online (Sandbox Code Playgroud)

相反,如果您有兴趣运行curl直到响应显示特定的 HTTP 状态:

until [ \
  "$(curl -s -w '%{http_code}' -o /dev/null "http://example.com/foo.html")" \
  -eq 200 ]
do
  sleep 5
done
Run Code Online (Sandbox Code Playgroud)

-w指示在完成传输后curl显示由格式字符串(此处为 )指定的信息。%{http_code}