Getting the Age of a File in Days in Bash

Gatting the age of a file in days is sometimes useful in scripts.

The date +%s command will give the current time in epoch seconds. It can be handily combined with -r, which causes date to use the modification time of a file rather than the current time. For example:

$ ls -l /etc/hosts
-rw-r--r-- 1 root root 3031 Mar 22 20:23 /etc/hosts

Our hosts file was last modified on March 22nd.  Converting that date to "epoch" time, gives us the age of the file (since Jan 1970), in seconds:
$ date -r /etc/hosts +%s 

And subtracting that number from the current time, also in epoch seconds, using Bash arithmetic:

$ echo $(( $(date +%s) - $(date -r /etc/hosts +%s) ))

The /etc/hosts file is 2921768 seconds old. More Bash arithmetic will convert that age to days (86400 being the number of seconds in a day):

$ echo $(( ($(date +%s) - $(date -r /etc/hosts +%s)) / 86400 ))

That is an integer, as the shell cannot do floating point. For that, use bc instead. Some escaping is needed though:

$ echo \( $(date +%s) - $(date -r /etc/hosts +%s) \) / 86400 | bc -l

or, to make is slightly simpler, just quote the whole calculation:

$ echo "( $(date +%s) - $(date -r /etc/hosts +%s) ) / 86400" | bc -l

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.