I'm writing a script to create backups of a folder and its contents. There is a prompt for the user to enter the folder name to be backed up. The backed up copies are to be named using this convention: original foldername_date and time of whatever file was last modified in folder. The script does the copying fine, but I'm stuck on how to extract the date and time of the last modified file.

Here is an example:

  1. user enters Documents/Graphite at the prompt so that the Graphite folder and its contents are copied
  2. within the Graphite folder there are files plus several subfolders containing files
  3. the most recently modified file within the Graphite folder and its subfolders is called index.js, located in the services subfolder, and it has a date/timestamp of 1/28/2020 14:28:54

    For the example outlined above, when the script runs two things are required to happen:
    a) the terminal outputs the following for the most recently modified file:
    2020-01-28 14:28:54 ./services/index.js
    b) the last modified date and timestamp of the services/index.js file are stored in a variable in this format 2020-01-28_14-28-54

    The purpose of storing the date/time in a variable is that it will be used to modify the copied folder's name.

The response in this post by @Heppo on 9/16/2011 at 18:21 recommends this for a similar use case:

find $1 -type f -print0 | xargs -0 stat --format '%Y :%y %n' | sort -nr | cut -d: -f2- | head

Which comes close for requirement a) above, except that it displays more than 1 file and the timestamp format is different. Despite plugging the command into explainshell.com, I'm not sure how to change it to fulfill requirement a).

Any guidance for how to go about getting the info for these two requirements would be appreciated, as I'm new to Linux.

1 Answer 1


Since you're using Ubuntu and have GNU find available, you could print the latest modification date using the -printf option.

find "$1" -type f -printf '%TY-%Tm-%Td_%TH-%TM-%TS\n' | sort -r | head -n1

would output something like


Unfortunately you would have to strip the fractional part of the seconds as there is no option to print the seconds without it.

lastmod=$(find "$1" -type f -printf '%TY-%Tm-%Td_%TH-%TM-%TS\n' | sort -r | head -n1)
lastmod=${lastmod%.*} # strip fractional part

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .