Bash – determine if date is beyond 90 days in bash

bashdatelinux

I need to fire off an alert to the security team if a users AWS access keys exceed 90 days old. I am doing this in bash.

So far my script is outputting the keys and the dates like this:

AKIAJS7KPHZCQRQ5FJWA : 2016-08-31T15:38:18Z
AKIAICDOHVTMEAB6RM5Q : 2018-02-08T03:55:51Z

How do I handle determining if the date is past 90 days old using that date format in bash?

I am using Ubuntu 18.04. I believe that the date format is ISO 8601. Please confirm/correct if that is wrong as well.

Best Answer

You can use GNU date to convert a date-time string into a number of seconds (since "the epoch", 1st January 1970). From there it's a simple arithmetic comparison

datetime='2016-08-31T15:38:18Z'
timeago='90 days ago'

dtSec=$(date --date "$datetime" +'%s')    # For "now", use $(date +'%s')
taSec=$(date --date "$timeago" +'%s')

echo "INFO: dtSec=$dtSec, taSec=$taSec" >&2

[ $dtSec -lt $taSec ] && echo too old
Related Question