Zsh Mailing List Archive
Messages sorted by:
Reverse Date,
Date,
Thread,
Author
Re: for loop file order
2026-11-16 13:58:10 -0500, Eric Postpischil:
> A solution I use for processing file names in the shell is to use “find” to print them with a null-character terminator and then use zsh’s read command with “no” delimiters, as in:
>
> find . -depth 1 -print0 | \
> while read -d '' File; do
> echo $File
> done
>
> Note the “’’” there is two apostrophes, not a quotation mark.
[...]
That adds more problems of its own.
- -depth 1 (FreeBSD and derivatives only) matches at depth 1,
but doesn't stop find from descending at depths deeper, so it
will waste time crawling the whole directory tree for only
outputting the files at depth 1.
You'd want the GNU style (and nowadays widely supported)
-mindepth 1 -maxdepth 1. Or the standard:
find . ! -name . -prune -print0
- find doesn't exclude hidden files by itself
- find doesn't sort files (and you'd need GNU or compatible sort
-z as you mentioned). And if you need to sort by mtime, size,
number of characters etc, it becomes more complicated and you
need to resort to the -printf of GNU find or recent versions
of FreeBSD combined with things like perl or more GNUisms.
- it adds a ./ prefix (which may actually be a good thing)
- you need IFS= read -rd '' File, or it won't work properly with
filenames ending (not *starting* thanks to the ./ prefix) in
space, tab or newline or containing backslashes.
- echo also means problems with backslashes. echo -E would help
here (and again the ./ prefix helps with filenames starting
with -)
- that pipe from find is the stdin of "read" but also of every
command running in the loop.
So for the equivalent of:
for file in *(N); do
cmd-that-may-read-stdin -- $file
done
You'd need something like:
while IFS= read -ru3 -d '' file; do
{
cmd-that-may-read-stdin -- $file
} 3<&-
done 3< <(
LC_ALL=C find . -mindepth 1 -maxdepth 1 ! -name '.*' -printf '%P\0' |
sort -z
)
For *(N-oL):
LC_ALL=C find -L . -mindepth 1 -maxdepth 1 ! -name '.*' -printf '%s\t%P\0' |
sort -zn | cut -zf2-
--
Stephane
Messages sorted by:
Reverse Date,
Date,
Thread,
Author