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 
1711139009

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

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

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 ))
33

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
33.82096064814814814814

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

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

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.