Compare Date to today's date in shell script

Hi Community!

Following on from this code in another thread:

#!/bin/bash
file_string=`/bin/cat date.txt | /usr/bin/awk '{print $5,$4,$7,$6,$8}'`
file_date=`/bin/date -d "$file_string"`
file_epoch=`/bin/date -d "$file_string" +%s`
now_epoch=`/bin/date +%s`

if [ "$file_epoch" -gt "$now_epoch" ]
then
        #let difference=$file_epoch-$now_epoch
       difference=`/usr/bin/expr $file_epoch - $now_epoch`
elif [ "$now_epoch" -gt "$file_epoch" ]
then
       #let difference=$now_epoch-$file_epoch
      difference=`/usr/bin/expr $now_epoch - $file_epoch`
else
        let difference=0
fi

if [ "$difference" -ge "172800" ]
then
        echo "More than 2 days between $file_date and now"
else
        echo "Less than 2 days between $file_date and now"
fi

The code above works with the following input file:

$ cat date.txt
Not After : Jul 28 14:09:57 2017 GMT
$ ./script.sh
More than 2 days between Fri 28 Jul 15:09:57 BST 2017 and now
$

But my target file just contains a date such as "10/02/2020"

I'm looking for a way to check if dates listed within a file are greater than 1 year.

The thread above is very close but the date format is not my use case.

What is the best way to achieve this?

Thanks in advance!

You should not need awk (or any command line text processor) to convert from various date formats to unixtime (epoch time) and back again.

I spent a few hours today on MQTT with various date and time formats, passing between PHP and Node.js (Javascript) and back, converting unixtime to various formatted date strings and back.

I did not require any text processing software to do this.

Working with dates and time is very standard these days, and we generally do not need text processors to format date and time strings, convert between various formats, and back. This is all "standard stuff" in computer science for quite some time.

Unfortunately, date does not immediately recognize your format. Depending on your bash and date versions, the request can be fulfilled in two - admittedly a bit complex - lines:

readarray -td/ DATARR <<< "10/02/2020"
if (( ( ( $(date +%s) - $(date -d"${DATARR[2]}/${DATARR[1]}/${DATARR[0]}" +%s)  ) / 86400 ) > 2 )); then printf "greater than 2 days\n"; else printf "less or equal 2 days\n"; fi
 less or equal 2 days

The readarr builtin can read your file.