0

I would like to get a list (or array) of all files in my current directory which is sorted by modification date. In the terminal, something like ls -lt works, but that should not be used in a bash script (http://mywiki.wooledge.org/BashPitfalls#for_i_in_.24.28ls_.2A.mp3.29)...

I tried to use the -nt opterator (https://tips.tutorialhorizon.com/2017/11/18/nt-file-test-operator-in-bash/) but I am hoping that there is a more simple and elegant solution to this.

hwerner
  • 49
  • 4

1 Answers1

1

This might help you:

In bash with GNU extensions:

Creating an array

mapfile -d '' a < <(find -maxdepth 1 -type f "%T@ %p\0" | sort -z -k1,1g | cut -z -d ' ' -f2)

or looping over the files:

while read -r -d '' _ file; do
   echo "${file}"
done < <(find -maxdepth 1 -type f "%T@ %p\0" | sort -z -k1,1g)

Here we build up a list of files with the NULL-character as the delimiter. The field itself consists of the modification date in the epoch followed by a space and the file name. We use sort to sort that list by modification date. The output of this is passed to a while loop that reads the fields per zero-terminated record. The first field is the modification date which we read in _ and the remainder is passed to file.

In ZSH:

If you want to use another shell like zsh, you can just do something like:

a=( *(Om) )

or

for file in *(Om); do echo "${file}"; done

here Om is a glob-modifier that tells ZSH to sort the output by modification date.

kvantour
  • 25,269
  • 4
  • 47
  • 72