英文:
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 "$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 "Trying $url..."
until check_url_success "$url"; do
echo "Failed. Retrying..."
sleep $retry_timer # Add a delay before retrying
done
echo "Success for $url!"
sleep $success_timer # Add a delay of 2 min when curl ping succeeded
done
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论