在循环中迭代直到满足条件。

huangapple go评论73阅读模式
英文:

Iterating over a loop till condition is met

问题

我有一个需求,我希望我的Shell脚本能够读取一个文本文件,其中包含一些URL。我希望它能够使用curl逐个访问这些URL。该网站可能会返回“成功”或“失败”之一。
如果在第一次尝试中URL显示失败,那么脚本应该再次迭代,尝试访问相同的URL,直到它显示成功,然后继续处理第二个URL。

sample.txt

abc.com
xyz.com

我考虑使用while循环中的until循环,但不确定它是否会起作用。有人能帮助我吗?

正如我所说,我考虑在while循环中使用until循环,但不确定它是否会起作用。

英文:

I have a requirement wherein I want my shell script to read a text file having some URLs in it. I want it to hit those with the help of curl one by one. The website can return say either "success" or a "failure".
If in case in first attempt the URL showed a failure then script should iterate again and trying hitting same URL until it shows a success and thereafter proceed with second URL.

sample.txt

abc.com
xyz.com

I thought of using a until loop in while loop but not sure if it will work. Can someone pls help me out.

As said I thought of using until loop in a while loop but not sure if it will work

答案1

得分: 1

使用 until 循环:

#!/bin/bash

retry_timer=5
success_timer=120

function check_url_success() {
  local url=$1
  local response=$(curl -s /dev/null "$url")
  if [ "$response" == "success" ]; then
    return 0
  else
    return 1
  fi
}

urls=()
while IFS= read -r url; do
  urls+=("$url")
done < "sample.txt"

for url in "${urls[@]}"; do
  echo "尝试 $url..."
  
  until check_url_success "$url"; do
    echo "失败,正在重试..."
    sleep $retry_timer  # 在重试前添加延迟
  done
  echo "成功访问 $url!"
  sleep $success_timer # 当 curl 请求成功时添加 2 分钟的延迟
done
英文:

Using until loop :

#!/bin/bash

retry_timer=5
success_timer=120

function check_url_success() {
  local url=$1
  local response=$(curl -s /dev/null &quot;$url&quot;)
  if [ &quot;$response&quot; == &quot;success&quot; ]; then
    return 0
  else
    return 1
  fi
}

urls=()
while IFS= read -r url; do
  urls+=(&quot;$url&quot;)
done &lt; &quot;sample.txt&quot;

for url in &quot;${urls[@]}&quot;; do
  echo &quot;Trying $url...&quot;
  
  until check_url_success &quot;$url&quot;; do
    echo &quot;Failed. Retrying...&quot;
    sleep $retry_timer  # Add a delay before retrying
  done
  echo &quot;Success for $url!&quot;
  sleep $success_timer # Add a delay of 2 min when curl ping succeeded
done

huangapple
  • 本文由 发表于 2023年7月31日 22:13:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76804463.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定