areuz areuz - 6 months ago 36
Bash Question

Sorting an array of pathnames (strings) [Bash]

I have seen way too many duplicates of this, but none of the answer codes or tips ever helped me, so I'm left confused.

#Contains something along the lines of
#/foo/bar/file1 /foo/bar/file2 /foo/bar/file3
#And I simply need
#/foo/bar/file3 /foo/bar/file2 /foo/bar/file1

output=($(for l in ${input[@]}; do echo $l; done | sort));
#Doesn't work, returns only the last entry from input

output=$(sort -nr ${input});
#Works, returns everything correctly reversed, but outputs the file contents and not the pathnames;
output=($(sort -nr ${input}));
#Outputs only the last entry and also its contents and not the pathname;

I tried many more options, but I'm not gonna fill this whole page with them, you get the gist.

Duplicates: (None of them helpful to me)

How can I sort the string array in linux bash shell?

How to sort an array in BASH

custom sort bash array

Sorting bash arguments alphabetically


You can use sort -r with printf, where input containg glob string to match your filenames:

sort -r <(printf "%s\n" $input)