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 ?

  • 1
    If you need to compare two dates try to convert them to MJD or UNIX time, for example: date +%s.
    – Eddy_Em
    Feb 4, 2013 at 10:21
  • 1
    @Eddy no it's not the date, It's the time I need to compare.
    – mtk
    Feb 4, 2013 at 10:24
  • 1
    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, 2013 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, 2013 at 10:49
  • 1
    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, 2013 at 11:16

2 Answers 2


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)}
  • 1
    ok cool. Just wanted to confirm that what I am doing is not crude or evil. Thanks for the suggestions.
    – mtk
    Feb 4, 2013 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.


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .