user1950349 user1950349 - 2 months ago 6
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?

#!/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.

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

You can use the script as follows, tested with 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
Comments