Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: for loop file order



On Mon, Nov 16, 2026 at 6:02 PM Mark J. Reed <markjreed@xxxxxxxxx> wrote:
>
> To be clear, you could certainly always do this:
>
>
> for aa in $(ls ...); do
>
>
> in any of the Bournish shells. Unfortunately, that splits the output of ls on whitespace and so will break if any of your filenames have a space inside them. The solution in my message is peculiar to zsh; it uses the ${(flags)"$(...)"} syntax to apply expansion flags to command substitution, which by itself has no place to put them. By quoting the output of ls (which by itself would create one giant string and execute your loop exactly once with aa set to that string - not helpful) and applying the (f) flag to split on newlines, you get the desired result without having to do a while read loop or similar.

This just moves the problem from white space in filenames breaking the
script to newlines in filenames breaking the script, though. I would
recommend never using ls to generate a list of filenames for use in a
script, only for looking at the output with your eyeballs.

-- 
Mikael Magnusson




Messages sorted by: Reverse Date, Date, Thread, Author