Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare time using date command

Say I want a certain block of a bash script executed 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 the date command.

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

like image 253
vehomzzz Avatar asked May 24 '10 18:05

vehomzzz


2 Answers

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.

like image 75
Cascabel Avatar answered Sep 20 '22 16:09

Cascabel


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

like image 22
seamus Avatar answered Sep 23 '22 16:09

seamus