unix command to find most recent directory created unix command to find most recent directory created shell shell

unix command to find most recent directory created


This is the answer to the question I think you are asking.

When I deal with many directories that have date/time stamps in the name, I always take the approach that you have which is YYYYMMDD - the great thing about that is that the date order is then also the alphabetical order. In most shells (certainly in bash and I am 90% sure of the others), the '*' expansion is done alphabetically, and by default 'ls' return alphabetical order. Hence

    ls | head -1    ls | tail -1

Give you the earliest and the latest dates in the directory.

This can be extended to only keep the last 5 entries etc.


lastdir=`ls -tr <parentdir> | tail -1`

I don't know how to make the backticks play nice with the commenting system here. Just replace those apostrophes with backticks.


After some experimenting, I came up with the following:

The unix stat command is useful here. The '-t' option causes stat to print its output in terse mode (all in one line), and the 13th element of that terse output is the unix timestamp (seconds since epoch) for the last-modified time. This command will list all directories (and sub-directories) in order from newest-modified to oldest-modified:

find -type d -exec stat -t {} \; | sort -r -n -k 13,13

Hopefully the "terse" mode of stat will remain consistent in future releases of stat !

Here's some explanation of the command-line options used:

find -type d                # only find directoriesfind -exec [command] {} \;  # execute given command against each *found* file.sort -r                     # reverse the sortsort -n                     # numeric sort (100 should not appear before 2!)sort -k M,N                 # only sort the line using elements M through N.

Returning to your original request, to copy files, maybe try the following. To output just a single directory (the most recent), append this to the command (notice the initial pipe), and feed it all into your 'cp' command with backticks.

| head --lines=1 | sed 's/\ .*$//'