Home > Enterprise >  Compare a date in a bash script
Compare a date in a bash script

Time:06-09

I am doing a script to evaluate the last connection of a user, for this, I get the last time it was connected, and I extract the user the date of the last connection, what I need to do now is to see if that date is greater or less than "2022-05-20" for example, but my problem is, that I do not know how to compare two dates in bash.

This is my code;

while [ $i -le $size_students ]
    do
        # Get the user's login
        login=$(sed -n "${i}p" xxxx.txt)
        # Get the user's data
        user_data=$(curl -X GET -H "Authorization: Bearer ${bearer_token}" "https://xxxxxxxxx/${login}/locations_stats" --globoff)
        # Get the user's last location
        last_lotaction=$(echo $user_data | jq -r '.' | cut -d "\"" -f 2 | grep -Eo '[0-9]{4}-[0-9]{2}-[0-9]{2}' | head -n 1)
        # if last_location is null or less than 2022-05-01, the user is not connected
        echo `$login: $last_location`

The output is:

EnzoZidane: 2022-03-17

CodePudding user response:

With your date formats, a simple string comparison should yield the desired result:

#!/bin/bash
[[ 2022-05-20 > 2022-05-19 ]] && echo yes
[[ 2022-05-20 < 2022-05-19 ]] || echo no

CodePudding user response:

If you can guarantee that all your months and days are formatted with a leading zero where applicable, and the order is year-month-day, then you can probably just use a string comparison:

if [[ "2022-05-31" < "2022-06-01" ]] 
then 
    echo true
fi

CodePudding user response:

Convert all you dates to epoch first, then you can compare two integers:

if [[ $(date --date="$last_location"  %s) < $(date --date="2022-05-20"  %s) ]]; then
    echo "before"
else
    echo "after"
fi

Epoch time is always an integer number.

  • Related