If file modification date is older than N days

Several approaches are available. One is just to ask find to do the filtering for you:

if [[ $(find "$filename" -mtime +100 -print) ]]; then
  echo "File $filename exists and is older than 100 days"
fi

Another is to use GNU date to do the math:

# collect both times in seconds-since-the-epoch
hundred_days_ago=$(date -d 'now - 100 days' +%s)
file_time=$(date -r "$filename" +%s)

# ...and then just use integer math:
if (( file_time <= hundred_days_ago )); then
  echo "$filename is older than 100 days"
fi

If you have GNU stat, you can ask for a file’s timestamp in seconds-since-epoch, and do some math yourself (though this will potentially be a bit off on the boundary cases, since it’s counting seconds — and not taking into account leap days and such — and not rounding to the beginning of a day):

file_time=$(stat --format="%Y" "$filename")
current_time=$(( date +%s ))
if (( file_time < ( current_time - ( 60 * 60 * 24 * 100 ) ) )); then
  echo "$filename is older than 100 days"
fi

Another option, if you need to support non-GNU platforms, is to shell out to Perl (which I’ll leave it to others to demonstrate).

If you’re interested more generally in getting timestamp information from files, and portability and robustness constraints surrounding same, see also BashFAQ #87.

Leave a Comment