Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two dates in Bash in MAC OSX

Tags:

date

bash

macos

I'm new to Bash, apologies in advance.


Set-up

I have a particular end date end which depends on a particular starting date s and a period length p such that, end=s+p.


Problem

I want to execute a command if and only if today's date is before or equal to the end date.

That is: execute command iff date ≤ end.


Code

s='20/09/2017'
p='1'
end=$( date -j -v +"$p"d -f "%d/%m/%Y" "$s")

if [[ date < “$end” ]];
then
   echo 'ok'
fi

There are 2 things not the way they should be,

  1. p=1 implies end = '21/09/2017' < date = '26/09/2017', but still I get an ok.
  2. I use date < “$end” but I want date ≤ “$end”

How to correct 1 and 2?

like image 412
LucSpan Avatar asked Dec 12 '25 14:12

LucSpan


2 Answers

When you format the date like YYYYMMDD you can simply use an alphanumeric comparison:

start=$(date +'%Y%m%d')
end=$(date +'%Y%m%d')

# -gt means greater than - for example.
# check `help test` to get all available operators
if [ $start -gt $end ] ; then ...
like image 61
hek2mgl Avatar answered Dec 14 '25 09:12

hek2mgl


First you need to use a date format which is lexicographical, meaning the big units come first. I highly recommend the ISO standard YYYY-MM-DD or YYYYMMDD. Second, <= can be written as -le (less or equal).

like image 32
John Zwinck Avatar answered Dec 14 '25 08:12

John Zwinck