How to Sort Files by Modification Time

findlssorttimestampswildcards

I've seen many questions and answers here using a construction along the lines of

list_dir=`ls -t /path/to/dir/`
for i in $list_dir; do

or

ls -t | while read i; do

Now, I know that you shouldn't use ls in scripts because it breaks easily; but I can't find a better way of operating on files in order from last-modified to most-recently-modified (or vice versa).

I can use something like:

find . -type f -printf '%T@ %p\n' | sort -n | cut -d ' ' -f 2- | while read i; do...

…but this will still break with any files that have newlines in their names, and is much uglier to boot. Is there a better way?

Best Answer

"Don't use ls in scripts" is a problem with POSIX ls "only"; for GNU ls see --quoting-style=.

GNU sort solves the problem with --zero-terminated.

If it must be compatible then you could use find ... -exec for passing one file name at a time to a script which does the escaping. If at least bash is available:

start cmd:> testfunc () { echo "${1//$'\n'/\n}"; }
start cmd:> testfunc a$'\n'b
a\nb