Ubuntu – How to display modification time of a file

bashcommand linescripts

I'd like a method to find and print the modified time of a file, for use within a bash script.

I have come up with:

ls -l $filename | cut -d ' ' -f '6-8'

Which outputs:

Jul 26 15:05

Though I'd like to avoid parsing ls, also it'd be useful to have the year in there.

Ideally I'd like to see an output similar to the default output of the date command.

Tue Jul 26 15:20:59 BST 2016

What other useful methods are available?

Best Answer

Don't use ls, this is a job for stat:

stat -c '%y' filename

-c lets us to get specific output, here %y will get us the last modified time of the file in human readable format. To get time in seconds since Epoch use %Y:

stat -c '%Y' filename

If you want the file name too, use %n:

stat -c '%y : %n' filename
stat -c '%Y : %n' filename

Set the format specifiers to suit your need. Check man stat.

Example:

% stat -c '%y' foobar.txt
2016-07-26 12:15:16.897284828 +0600

% stat -c '%Y' foobar.txt
1469513716

% stat -c '%y : %n' foobar.txt
2016-07-26 12:15:16.897284828 +0600 : foobar.txt    

% stat -c '%Y : %n' foobar.txt
1469513716 : foobar.txt

If you want the output like Tue Jul 26 15:20:59 BST 2016, use the Epoch time as input to date:

% date -d "@$(stat -c '%Y' a.out)" '+%a %b %d %T %Z %Y'
Tue Jul 26 12:15:21 BDT 2016

% date -d "@$(stat -c '%Y' a.out)" '+%c'               
Tue 26 Jul 2016 12:15:21 PM BDT

% date -d "@$(stat -c '%Y' a.out)"
Tue Jul 26 12:15:21 BDT 2016

Check date's format specifiers to meet your need. See man date too.

Related Question