[bash] Print a file's last modified date in Bash

I can't seem to find how to print out the date of a file. I'm so far able to print out all the files in a directory, but I need to print out the dates with it.

I know I need to attach a date format with the echo of the entry, but all I can't find the correct format.

echo "Please type in the directory you want all the files to be listed"

read directory 

for entry in "$directory"/*
do
  echo "$entry"
done

This question is related to bash shell file date unix

The answer is


Isn't the 'date' command much simpler? No need for awk, stat, etc.

date -r <filename>

Also, consider looking at the man page for date formatting; for example with common date and time format:

date -r <filename> "+%m-%d-%Y %H:%M:%S"

I wanted to get a file's modification date in YYYYMMDDHHMMSS format. Here is how I did it:

date -d @$( stat -c %Y myfile.css ) +%Y%m%d%H%M%S

Explanation. It's the combination of these commands:

stat -c %Y myfile.css # Get the modification date as a timestamp
date -d @1503989421 +%Y%m%d%H%M%S # Convert the date (from timestamp)

You can use:

ls -lrt filename |awk '{print "%02d",$7}'

This will display the date in 2 digits.

If between 1 to 9 it adds "0" prefix to it and converts to 01 - 09.

Hope this meets the expectation.


If file name has no spaces:

ls -l <dir> | awk '{print $6, " ", $7, " ", $8, " ", $9 }'

This prints as the following format:

 Dec   21   20:03   a1.out
 Dec   21   20:04   a.cpp

If file names have space (you can use the following command for file names with no spaces too, just it looks complicated/ugly than the former):

 ls -l <dir> | awk '{printf ("%s %s %s ",  $6,  $7, $8); for (i=9;   i<=NF; i++){ printf ("%s ", $i)}; printf ("\n")}'

Best is

date -r filename +"%Y-%m-%d %H:%M:%S"

Adding to @StevePenny answer, you might want to cut the not-so-human-readable part:

stat -c%y Localizable.strings | cut -d'.' -f1

On OS X, I like my date to be in the format of YYYY-MM-DD HH:MM in the output for the file.

So to specify a file I would use:

stat -f "%Sm" -t "%Y-%m-%d %H:%M" [filename]

If I want to run it on a range of files, I can do something like this:

#!/usr/bin/env bash
for i in /var/log/*.out; do
  stat -f "%Sm" -t "%Y-%m-%d %H:%M" "$i"
done

This example will print out the last time I ran the sudo periodic daily weekly monthly command as it references the log files.


To add the filenames under each date, I would run the following instead:

#!/usr/bin/env bash
for i in /var/log/*.out; do
  stat -f "%Sm" -t "%Y-%m-%d %H:%M" "$i"
  echo "$i"
done

The output would was the following:

2016-40-01 16:40
/var/log/daily.out
2016-40-01 16:40
/var/log/monthly.out
2016-40-01 16:40
/var/log/weekly.out

Unfortunately I'm not sure how to prevent the line break and keep the file name appended to the end of the date without adding more lines to the script.


PS - I use #!/usr/bin/env bash as I'm a Python user by day, and have different versions of bash installed on my system instead of #!/bin/bash


EDITED: turns out that I had forgotten the quotes needed for $entry in order to print correctly and not give the "no such file or directory" error. Thank you all so much for helping me!

Here is my final code:

    echo "Please type in the directory you want all the files to be listed with last modified dates" #bash can't find file creation dates

read directory

for entry in "$directory"/*

do
modDate=$(stat -c %y "$entry") #%y = last modified. Qoutes are needed otherwise spaces in file name with give error of "no such file"
modDate=${modDate%% *} #%% takes off everything off the string after the date to make it look pretty
echo $entry:$modDate

Prints out like this:

/home/joanne/Dropbox/cheat sheet.docx:2012-03-14
/home/joanne/Dropbox/Comp:2013-05-05
/home/joanne/Dropbox/Comp 150 java.zip:2013-02-11
/home/joanne/Dropbox/Comp 151 Java 2.zip:2013-02-11
/home/joanne/Dropbox/Comp 162 Assembly Language.zip:2013-02-11
/home/joanne/Dropbox/Comp 262 Comp Architecture.zip:2012-12-12
/home/joanne/Dropbox/Comp 345 Image Processing.zip:2013-02-11
/home/joanne/Dropbox/Comp 362 Operating Systems:2013-05-05
/home/joanne/Dropbox/Comp 447 Societal Issues.zip:2013-02-11

For the line breaks i edited your code to get something with no line breaks.

#!/bin/bash
for i in /Users/anthonykiggundu/Sites/rku-it/*; do
   t=$(stat -f "%Sm"  -t "%Y-%m-%d %H:%M" "$i")
   echo $t : "${i##*/}"  # t only contains date last modified, then only filename 'grokked'- else $i alone is abs. path           
done

Examples related to bash

Comparing a variable with a string python not working when redirecting from bash script Zipping a file in bash fails How do I prevent Conda from activating the base environment by default? Get first line of a shell command's output Fixing a systemd service 203/EXEC failure (no such file or directory) /bin/sh: apt-get: not found VSCode Change Default Terminal Run bash command on jenkins pipeline How to check if the docker engine and a docker container are running? How to switch Python versions in Terminal?

Examples related to shell

Comparing a variable with a string python not working when redirecting from bash script Get first line of a shell command's output How to run shell script file using nodejs? Run bash command on jenkins pipeline Way to create multiline comments in Bash? How to do multiline shell script in Ansible How to check if a file exists in a shell script How to check if an environment variable exists and get its value? Curl to return http status code along with the response docker entrypoint running bash script gets "permission denied"

Examples related to file

Gradle - Move a folder from ABC to XYZ Difference between opening a file in binary vs text Angular: How to download a file from HttpClient? Python error message io.UnsupportedOperation: not readable java.io.FileNotFoundException: class path resource cannot be opened because it does not exist Writing JSON object to a JSON file with fs.writeFileSync How to read/write files in .Net Core? How to write to a CSV line by line? Writing a dictionary to a text file? What are the pros and cons of parquet format compared to other formats?

Examples related to date

How do I format {{$timestamp}} as MM/DD/YYYY in Postman? iOS Swift - Get the Current Local Time and Date Timestamp Typescript Date Type? how to convert current date to YYYY-MM-DD format with angular 2 SQL Server date format yyyymmdd Date to milliseconds and back to date in Swift Check if date is a valid one change the date format in laravel view page Moment js get first and last day of current month How can I convert a date into an integer?

Examples related to unix

Docker CE on RHEL - Requires: container-selinux >= 2.9 What does `set -x` do? How to find files modified in last x minutes (find -mmin does not work as expected) sudo: npm: command not found How to sort a file in-place How to read a .properties file which contains keys that have a period character using Shell script gpg decryption fails with no secret key error Loop through a comma-separated shell variable Best way to find os name and version in Unix/Linux platform Resource u'tokenizers/punkt/english.pickle' not found