Monday, February 21, 2022

[SOLVED] Compare dates with bash

Issue

I need to collect user input to determine date and then compare that with today's date.

Here is what I have:

echo "Enter Current Date (YYMMDD):"
read date
current_date= date +"%y%m%d"
if [ "$date" == "$current_date" ]; then
        echo "match"
   else
        echo "no match"
fi  

It prints no match for when it is expected to be a match and no match.


Solution

Try this:

echo "Enter Current Date (YYMMDD):"
read date
current_date=`date +"%y%m%d"`

if [ "$date" = "$current_date" ]; then
        echo "match"
   else
        echo "no match"
fi

Change is on this line :

current_date=`date +"%y%m%d"`

Reason: In your code, you are using current_date= date +"%y%m%d". Though your intention was to use the date command to generate the current date, this line behaves differently (becomes equivalent to current_date= ; date +"%y%m%d"; and results in current_date being empty. You can echo $current_date to verify this. With the correction provided, we are executing the date command and saving the output to current_date variable. Hope it is clear now. I don't know how to explain in a better way... :-)



Answered By - Arjun Mathew Dan
Answer Checked By - David Goodson (WPSolving Volunteer)