Linux Command Line – Get Last Change Time of Directory Recursively

command linelinux

How can I get the last time any of the files in a directory or its subdirectories has changed?
e.g

Dir - changed 1/1/1
    Sub Dir 1 - changed 2/1/1
        Sub Dir 2 - changed 3/1/1
            File 1 - changed 10/1/1
    File 2 - change 5/1/1

The output for this for Dir should be 10/1/1 (File 1 was the last modified one). Getting the last file name to be modified is a bonus but isn't necessary.

Best Answer

find <dir> -type f -printf '%T@\t%p\n' | sort -r -k1 | head -n1 returns a line in the form:

<seconds since epoch[1]><tab><filename>

Alias or put in a script like in the following example to print file name or date.


Let's create a testing tree:

$ date -u; mkdir -p a/{b,c,d}/{e,f,g}
Sat May 28 17:37:52 UTC 2011

$ date -u; touch a/{b,c,d}/{e,f,g}/{foo,bar,baz}; sleep 1; date -u; touch a/c/f/bar
Sat May 28 17:38:17 UTC 2011
Sat May 28 17:38:18 UTC 2011

Get date of a:

$ date -ud @$(find a -type f -printf '%T@\t%p\n' | sort -r -k1 | head -n1 | cut -f1)
Sat May 28 17:38:18 UTC 2011

Get path of the file:

$ find a -type f -printf '%T@\t%p\n' | sort -r -k1 | head -n1 | cut -f2
a/c/f/bar

[1]: See Unix time on Wikipedia for an explanation of "Unix epoch".


Script example:

#!/bin/sh
if test ! -d "${1:-.}"
then
    echo not a directory: ${1:-.} >&2
    exit 1
fi
date -d @$(find "${1:-.}" -type f -printf '%T@\t%p\n' | sort -r -k1 | head -n1 | cut -f1)

Call with or without <dir> as argument. It will use the current directory without.

Related Question