Get mtime of specific file using Bash?

stat can give you that info:

filemtime=$(stat -c %Y myfile.txt)

%Y gives you the last modification as "seconds since The Epoch", but there are lots of other options; more info. So if the file was modified on 2011-01-22 at 15:30 GMT, the above would return a number in the region of 1295710237.

Edit: Ah, you want the time in days since it was modified. That's going to be more complicated, not least because a "day" is not a fixed period of time (some "days" have only 23 hours, others 25 — thanks to daylight savings time).

The naive version might look like this:

filemtime=$(stat -c %Y "$1")
currtime=$(date +%s)
diff=$(( (currtime - filemtime) / 86400 ))
echo $diff

...but again, that's assuming a day is always exactly 86,400 second long.

More about arithmetic in bash here.


AGE=$(perl -e 'print -M $ARGV[0]' $file)

will set $AGE to the age of $file in days, as Perl's -M operator handles the stat call and the conversion to days for you.

The return value is a floating-point value (e.g., 6.62849537 days). Add an int to the expression if you need to have an integer result

AGE=$(perl -e 'print int -M $ARGV[0]' $file)

Ruby and Python also have their one-liners to stat a file and return some data, but I believe Perl has the most concise way.


The date utility has a convenient switch for extracting the mtime from a file, which you can then display or store using a format string.

date -r file "+%F"
# 2021-01-12
file_mtime=$(date -r file "+%F")

See man date, the output of date is controlled by a format string beginning with "+"

Useful format strings for comparing many dates might include:

"+%j": day of year
"+%s": unix epoch time

Arithmetic with dates is a bit of a pain in bash, so if you need relative time that will work in all corner cases, you may be better off with another language.

Tags:

Linux

Shell

Bash