determine if date is beyond 90 days in bash

8,959

Solution 1

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

Solution 2

The below script will read the format you presented above, but if you already have the values in existing variables, you could consolidate the code:

#!/bin/bash
cutoff=$(date -d '90 days ago' +%s)
while read -r key colon date
do
  age=$(date -d "$date" +%s)
  if (($age < $cutoff))
  then
    printf "Warning! key %s is older than 90 days\n" "$key" >&2
  fi
done < input
Share:
8,959

Related videos on Youtube

user99201
Author by

user99201

Updated on September 18, 2022

Comments

  • user99201
    user99201 almost 2 years

    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.