Issue
I believe directories should be, by default, sorted by last modified content with ls -lt
. But it turns out not to be the case, at least in my CentOS 7 system. Please see the terminal output below.
It seems like the directories are sorted as expected when files are CREATED, but not when they are MODIFIED.
How could I have them sorted by the last modification time of anything inside it?
[chinazzo@potzblix test]$ mkdir dir1
[chinazzo@potzblix test]$ mkdir dir2
[chinazzo@potzblix test]$ echo "Create in dir1" > dir1/file
[chinazzo@potzblix test]$ ls -lta
total 4
drwxrwxr-x. 2 chinazzo chinazzo 18 Jan 19 11:55 dir1 # Ok
drwxrwxr-x. 4 chinazzo chinazzo 30 Jan 19 11:55 .
drwxrwxr-x. 2 chinazzo chinazzo 6 Jan 19 11:55 dir2
drwx------. 31 chinazzo chinazzo 4096 Jan 19 11:49 ..
[chinazzo@potzblix test]$ echo "Create in dir2" > dir2/file
[chinazzo@potzblix test]$ ls -lta
total 4
drwxrwxr-x. 2 chinazzo chinazzo 18 Jan 19 11:56 dir2 # Ok
drwxrwxr-x. 2 chinazzo chinazzo 18 Jan 19 11:55 dir1
drwxrwxr-x. 4 chinazzo chinazzo 30 Jan 19 11:55 .
drwx------. 31 chinazzo chinazzo 4096 Jan 19 11:49 ..
[chinazzo@potzblix test]$ echo "Mod in dir1" >> dir1/file
[chinazzo@potzblix test]$ ls -lta
total 4
drwxrwxr-x. 2 chinazzo chinazzo 18 Jan 19 11:56 dir2
drwxrwxr-x. 2 chinazzo chinazzo 18 Jan 19 11:55 dir1 # Not ok, notice mtime 11:55
drwxrwxr-x. 4 chinazzo chinazzo 30 Jan 19 11:55 .
drwx------. 31 chinazzo chinazzo 4096 Jan 19 11:49 ..
[chinazzo@potzblix test]$ ls -lta dir1
total 4
-rw-rw-r--. 1 chinazzo chinazzo 27 Jan 19 11:56 file # but file (in dir1) mtime 11:56
drwxrwxr-x. 2 chinazzo chinazzo 18 Jan 19 11:55 .
drwxrwxr-x. 4 chinazzo chinazzo 30 Jan 19 11:55 ..
Solution
Use find:
find . -type d -printf "%Ts/%f\n" | sort -n
Search for only directories and then print the last modification time in epoch format (%Ts) as well as the directory name (%f). Pipe the output to sort -n to order the directories by modification time.
Answered By - Raman Sailopal Answer Checked By - Terry (WPSolving Volunteer)