I have a Bash script that has an array called myarray.

This array contains complete file location paths for 4 files.

What I am trying to do is sort the array elements by the file creation date.

So just as a quick example, if I have the following 4 files in the array:

/tmp/file1.txt (in index 0)
/tmp/test/file1.txt (in index 1)
/tmp/test1/file1.txt (in index 2)
/tmp/test2/file1.txt (in index 3)

...and the file in index 2 has newer creation date then the others, it should be sorted into index 1 and so on.

I originally thought the following would do it:

myarray=($(for each in ${myarray[@]}; do echo $each; done | sort -n))

But if I look at the array contents I do not see the newest file in index 0.

Would anyone know of a way to accomplish this in bash?


1 Answer 1


The following sorts the files by the modification date, as creation date isn't supported on the system I tested the script on. Replacing %Y with %W should output the creation time if supported.

#! /bin/bash
while IFS= read -r line ; do
done < <(
    for f in "${files[@]}" ; do
        echo $(stat -c %Y -- "$f")$'\t'"$f"
    done | sort -nk1,1 | cut -t $'\t' -f2-

echo "${sorted[@]}"

It works for files with spaces in their names. Filenames containing newlines can break it, but you don't use newlines in filenames, right?

Not the answer you're looking for? Browse other questions tagged .