user1950349 user1950349 - 1 year ago 70
Bash Question

call curl between particular period of time within day

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.

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?


while true
curl -s -m 2 "some_url" 2>&1 | grep "hello"
sleep 15m

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.

And if it is before 3 PM then it will keep sleeping until it is passed 3 PM.

I have to add this logic within script and I can't use cron here.

Answer Source

You can use the script as follows, tested with GNU date


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'
    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                                  

[[ $retCode -eq 1 ]] && echo "String not found" >> /dev/stderr  # If the search string is not found till the last minute, print the error message
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download