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?
Don't use
ls
, this is a job forstat
:-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
:If you want the file name too, use
%n
:Set the format specifiers to suit your need. Check
man stat
.Example:
If you want the output like
Tue Jul 26 15:20:59 BST 2016
, use the Epoch time as input todate
:Check
date
's format specifiers to meet your need. Seeman date
too.I tried
but if the date is less than 10 it misses the time. This because of the extra space before the date if less than 10. Try this:
The awk command prints the fields separated by all spaces (-F ' '). Hope it works. I know this doesn't answer the original question but just a clarification on the ls command for just date and time. When you Google "ubuntu get date and time of file" it lists this question at the top, which is what I was looking for, since I don't need the year also. For year, date and time, you could try one of the commands below. %m prints month number. %b prints month abbreviation: Drop the %H:%M if you don't need the hour and minute. %-d doesn't print leading zero for the day of the month.