views:

63

answers:

2

Say I want a certain block of bash script execute only if it is between 8 am (8:00) and 5 pm (17:00), and do nothing otherwise. The script is running continuously

So far I am using date command.

How to use it compare it current time within the range?

Thanks

+3  A: 

Just check if the current hour of the day is between 8 and 5 - since you're using round numbers, you don't even have to muck around with minutes:

hour=$(date +%H)
if [ "$hour" -lt 17 -a "$hour" -ge 8 ]; then
    # do stuff
fi

Of course, this is true at 8:00:00 but false at 5:00:00; hopefully that's not a big deal.

For more complex time ranges, an easier approach might be to convert back to unix time where you can compare more easily:

begin=$(date --date="8:00" +%s)
end=$(date --date="17:00" +%s)
now=$(date +%s)
# if you want to use a given time instead of the current time, use
# $(date --date=$some_time +%s)

if [ "$begin" -le "$now" -a "$now" -le "$end" ]; then
    # do stuff
fi

Of course, I have made the mistake of answering the question as asked. As seamus suggests, you could just use a cron job - it could start the service at 8 and take it down at 5, or just run it at the expected times between.

Jefromi
shouldn't this be end=$(date --date="17:00" +%s)?
vehomzzz
@Andrei: Definitely. Sorry about that - got it right in the first example, at least...
Jefromi
+1  A: 

Why not just use a cron job?

Otherwise

if [[ `date +%H` -ge 8 && `date +%H` -lt 17 ]];then
    do_stuff()
fi

will do the job

seamus
How would you use cron job in this case?
vehomzzz
The problem with a cron job is that it will start the job at or during the times specified and can do that periodically, but it does nothing about ending a job if it's still running at the end of a time period. So, for some uses, the date comparison method is better.
Dennis Williamson
`* 8-17 * * * do_stuff() # cron job run every minute between 8am and 5pm``1 17 * * * kill_stuff() # kill task at 17:01`
seamus