2

I try to understand how to use Zsh glob qualifiers with ls.

An article on the internet says that to sort the files from largest to smallest, I can use ls *(oL).

  • o<sort> - Sort files depending on the value of <sort>
  • O<sort> - Like o, but sort in descending order

The value of <sort> can be:

  • n - Sort by name (the default).
  • L - Sort by size.
  • l - Sort by number of links.
  • a - Sort by last access.
  • m - Sort by last modification.
  • c - Sort by last inode change.
  • d - Files in subdirectories appear before.
  • N - Don’t sort anything.

For example:

# Sort files from the smallest to the largest
ls *(oL)

But ls *(oL) doesn't list files in this way for me, ls *(On) doesn't list files in reverse alphabetical order, ls *(om) doesn't sort files by modification date (and there is no difference if you run ls *(Om)). All the commands list files in regular alphabetical order, from A to Z, and that's it. It seems ls ignores Zsh globs?

I should say that in other situations Zsh globs seems to work correctly for me. For example, print -rC1 *(.) prints only files, without directories.

zsh 5.9 (x86_64-apple-darwin23.0)

0

1 Answer 1

7

ls does its own sorting. To disable that, and display the files as they are given (by the glob expansion), use -f on macOS:

ls -f -- *(oL)

To list directories without listing their contents, add -d. For single-column output, add -1.

5
  • 3
    @jsx97 printf '%s\n' *(oL) perhaps? Commented May 17 at 8:36
  • @ChrisDavies Chris, I have deleted my first two comments. It seems your comment is to one of them?
    – jsx97
    Commented May 17 at 8:38
  • @jsx97 I don't have my Mac on at the moment to check, but it seem to me that if you're suggesting ls -1df *(oL) then printf would be simpler Commented May 17 at 8:46
  • 1
    The -f option is also specified by POSIX, where it is stated that it should "-f List the entries in directory operands in the order they appear in the directory." The OpenBSD manual for ls is more brief: -f Output is not sorted. The default behavior of ls, without any options, is to sort names according to the collating sequence in the current locale. Something to note is that the POSIX ls(1) manual page also states "The use of -f with -R or -d produces unspecified results". Commented May 17 at 9:44
  • 1
    @Vilinkameni right, all this is annoyingly platform-specific. The default behaviour in the scenario given here (where all files are specified as operands) is slightly more complex: “If more than one operand is specified, ls shall write non-directory operands first; it shall sort directory and non-directory operands separately according to the collating sequence in the current locale.” Commented May 17 at 10:02

You must log in to answer this question.

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