I have to execute a URL using curl and if the output contains a "hello" string, then I will exit successfully out of the shell script otherwise I keep retrying till 8 AM in the morning and then exit with an error message if it still doesn't contain that string.
我必须使用curl执行URL,如果输出包含一个“hello”字符串,那么我将成功地从shell脚本中退出,否则我将继续重试,直到早上8点,如果仍然不包含该字符串,则以错误消息退出。
I got below script but I am not able to understand how I can run while loop till 8 AM and if still curl output doesn't contain "hello" string?
我得到了下面的脚本,但是我无法理解如何在8点之前运行while循环,如果curl输出不包含“hello”字符串?
#!/bin/bash
while true
do
curl -s -m 2 "some_url" 2>&1 | grep "hello"
sleep 15m
done
So if it is after 3 PM then start making curl call until 8 AM and if it is successful with that curl call giving "hello" string, exit successfully otherwise after 8AM exit with error message.
如果是在下午3点以后,那么开始调用curl直到早上8点,如果这个curl调用成功地发出了“hello”字符串,那么在早上8点之后将成功退出,并发出错误消息。
And if it is before 3 PM then it will keep sleeping until it is passed 3 PM.
如果是在下午3点之前,它会一直睡到下午3点。
I have to add this logic within script and I can't use cron here.
我必须在脚本中添加这个逻辑,我不能在这里使用cron。
2 个解决方案
#1
1
You can use the script as follows, tested with GNU date
您可以使用下面的脚本,使用GNU date进行测试
#/bin/bash
retCode=0 # Initializing return code to of the piped commands
while [[ "$(date +"%T")" < '08:00:00' ]]; # loop from current time to next occurence of '08:00:00'
do
curl -s -m 2 "some_url" 2>&1 | grep "hello"
retCode=$? # Storing the return code
[[ $retCode ]] && break # breaking the loop and exiting on success
sleep 15m
done
[[ $retCode -eq 1 ]] && echo "String not found" >> /dev/stderr # If the search string is not found till the last minute, print the error message
#2
1
I think you can use date +%k
to retrieve current hour and compare with 8 AM and 13 PM. Code may like this
我认为您可以使用日期+%k来检索当前小时,并与上午8点和晚上13点进行比较。这样的代码可能
hour=`date +%k`
echo $hour
if [[ $hour -gt 15 || $hour -lt 8 ]]; then
echo 'in ranage'
else
echo 'out of range'
fi
#1
1
You can use the script as follows, tested with GNU date
您可以使用下面的脚本,使用GNU date进行测试
#/bin/bash
retCode=0 # Initializing return code to of the piped commands
while [[ "$(date +"%T")" < '08:00:00' ]]; # loop from current time to next occurence of '08:00:00'
do
curl -s -m 2 "some_url" 2>&1 | grep "hello"
retCode=$? # Storing the return code
[[ $retCode ]] && break # breaking the loop and exiting on success
sleep 15m
done
[[ $retCode -eq 1 ]] && echo "String not found" >> /dev/stderr # If the search string is not found till the last minute, print the error message
#2
1
I think you can use date +%k
to retrieve current hour and compare with 8 AM and 13 PM. Code may like this
我认为您可以使用日期+%k来检索当前小时,并与上午8点和晚上13点进行比较。这样的代码可能
hour=`date +%k`
echo $hour
if [[ $hour -gt 15 || $hour -lt 8 ]]; then
echo 'in ranage'
else
echo 'out of range'
fi