0

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?

marked as duplicate by Gilles bash Jan 14 '17 at 15:33

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

2

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
files=(*.txt)
while IFS= read -r line ; do
    sorted+=("$line")
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 or ask your own question.