Compare Two Dates in the Shell

I am trying to compare two dates in a shell script but I always get a wrong value. This is the code I am using:

currenttime=$(date +%H%M%S);
peak_time=$(date -d "$peak_time" '+%H%M%S');

num1=$(($peak_time-$currenttime))
echo $num1
if [ $num1 < 0 ]
then
  echo "peak time is bigger than current"
else
  echo "peak time is smaller than now"
fi

I always get

peak time is bigger than current

Even if it is smaller.

I tried again with static numbers, like this:

    if [ 10 < 0 ]
    then
        echo "peak time is bigger than current"
    else
        echo "peak time is smaller than now"
    fi

I always get peak time is bigger than current. So the if statement always prints the first sentence.

2

1 Answer

You should also get an error message when you run your script:

/home/terdon/scripts/foo.sh: line 7: 0: No such file or directory

This is because you are using < in a [ ], and that doesn't do arithmetic comparison, it's input redirection. So $num1 < 0 means "run the command $num1 and pass it the contents of file 0 as input". What you want is [ $num1 -lt 0 ], -lt means "less than".

Of course, your script doesn't make sense unless you are setting peak_time somewhere. This line:

peak_time=$(date -d "$peak_time" '+%H%M%S');

Will always print 000000 since when you run it, $peak_time has no value:

$ peak_time=$(date -d "$peak_time" '+%H%M%S');
$ echo $peak_time 
000000

You need to first set $peak_time and then convert it to a date. for example:

$ peak_time="10:05:31"
$ peak_time=$(date -d "$peak_time" '+%H%M%S');
$ echo $peak_time 
100531

So, a working version of your script would be:

#!/bin/bash
currenttime=$(date +%H%M%S);
peak_time="10:05:31"
peak_time=$(date -d "+1 hour" '+%H%M%S');

num1=$(($peak_time-$currenttime))
echo $num1
if [ $num1 -lt 0 ]
then
  echo "peak time is bigger than current"
else
  echo "peak time is smaller than now"
fi

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Elena Rostova

Elena Rostova

Lead Health, Wellness & Medical Journalist

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.

Share this article
Twitter Facebook Pinterest