Time condition exit loop

Hi All,

Requirement: The below script should automatically exit at 6pm everyday without manually killing the script

Tried running with the below shell script but found the script was still running when the time was 6:15pm. The script did not exit the while loop at 6pm

The script runs thorugh cron at 9AM Mon-Fri

Script xyz.sh

#!/bin/bash

hr=$(date +"%H")
while [ $hr -ge 9 -a $hr -lt 18 ]; do
some task is performed...
done

Thanks for your time!

Regards,
a1_win

Try this:

hr=$(date +"%H")
while [ $hr -ge 9 -a $hr -lt 18 ]
do
  some task is performed...
  sleep 5 # 5 secs; So you don't have a tight loop
  hr=$(date +"%H")
done

Hi Spacebar,

Thanks but this is not working!

Tried executing with the below command but it exited without running anything..

hr=$(date +"%H")
while [ $hr -ge 22 -a $hr -lt 01 ] # For example,tried time range between 22hrs and 01 AM as test 
do
   do some task....
  sleep 5 
  hr=$(date +"%H")
done

output:

-bash-3.2$ ./xyz.sh &
[1] 30061
-bash-3.2$
[1]+  Done                    ./xyz.sh
-bash-3.2$

Any other suggestion?

a1_win

There is no number that is greater or equal than 22 and at the same time lower than 1.

hr=$(date +"%H")
while [ $hr -ge 22 -o $hr -lt 01 ] # For example,tried time range between 22hrs and 01 AM as test 
do
   do some task....
  sleep 5 
  hr=$(date +"%H")
done

Hi a1_win,

Below script will execute in infinite while loop. When current time (cur_time) reaches script kill time (kill_time) it will exit the script.

#!/bin/bash

kill_time=1800
while true
do
          cur_time=`date "+%H%M"`
          if [ $cur_time -gt $kill_time ]; then
                    exit 5           # To find exit status of the script
          fi
          echo "Hello World"
          sleep 60                 # To execute script every 1 minute
done

The script doesn't understand "time" it is just seeing integers, so make sure your comparison numerical wise is valid.