Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I need to check for the current time and abort the script if it is not proper time of day I am supposed to run it. Also, if anyone else runs it, it should abort.

For example: I need my script to only run if it is started between 10 PM and and 2 AM (a 4 hour window).

Currently I am doing the following. Taking the time with date +%k%M and comparing with hard coded numbers

currTime=`date +%k%M`
    if [ $tempTime -gt 200 -a $tempTime -lt 2200 ]; then 
        echo "Time is between 2 AM and 10 PM. Aborting."
        exit 1
        echo "Time is after 10 PM and before 2 AM. Running normally."

check_time_to_run $currentTime

I would like to know if there is any other efficient method with respect to time comparision in sh or bash ?

share|improve this question
If you need to compare two dates try to convert them to MJD or UNIX time, for example: date +%s. – Eddy_Em Feb 4 '13 at 10:21
@Eddy no it's not the date, It's the time I need to compare. – mtk Feb 4 '13 at 10:24
I think, in seconds it would be better: currTime=$(date +%s); lower=$(date +%s --date="2:00"); upper=$(date +%s --date="22:00"); if [$currTime -gt $lower -a $currTime -lt $upper]; then – Eddy_Em Feb 4 '13 at 10:36
why not put the script in the crontab? this way you ensure that it runs at that specific time – BitsOfNix Feb 4 '13 at 10:49
As any user can change the time for a process with faketime, your script is not very safe. Using lockfiles is probably a better option. – jofel Feb 4 '13 at 11:16
up vote 5 down vote accepted

That looks perfect to me. What makes you think it should be improved?

Anyway, ways to improve it could be:

  • Use a smaller, quicker shell than bash like dash or pdksh.
  • use a shell that has date capabilities builtin like zsh or ksh93
  • use gawk (which is smaller than bash, but not than dash but could avoid the extra fork):


#! /usr/bin/gawk -f
BEGIN {now = strftime("%k%M")+0; exit(now > 200 && now < 2200)}
share|improve this answer
ok cool. Just wanted to confirm that what I am doing is not crude or evil. Thanks for the suggestions. – mtk Feb 4 '13 at 12:04

If external tools are allowed you might want to check dateutils.

Your "script'' becomes:

if dtest time --gt '02:00:00' && dtest time --lt '22:00:00'; then
    echo "Time is between 2 AM and 10 PM. Aborting."

Disclaimer: I am the author of said tool.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.