How to prevent `ls` from sorting the output

lssort

I have a specific order of files that I want to list if they exist; around 40 files. Some kind of precedence. So I tried:

ls -1d         /opt/foo/lib.jar /opt/bar/lib.jar

I expected this to list /opt/foo/lib.jar first if both exist.
But actually it prints the bar first and the foo after that.

Is there some way to make ls list the entries in the order given in parameters?
Or some alternative approach with find?

Best Answer

With GNU ls, you could try the -U option:

-U: do not sort; list entries in directory order

(though here, we're not listing the content of directories, so the part that matters is do not sort).

$ ls -1dU /opt/foo/lib.jar /opt/bar/lib.jar
/opt/foo/lib.jar
/opt/bar/lib.jar

Slightly more portable (works with GNU and FreeBSD ls, but not with traditional ls implementations and is not POSIX either), you can use ls -1df:

$ ls -1df /opt/foo/lib.jar /opt/bar/lib.jar
/opt/foo/lib.jar
/opt/bar/lib.jar
Related Question