How to silently get an empty string from a glob pattern with no matches

Turn on the null_glob option for your pattern with the N glob qualifier.

list_of_files=(*(N))

If you're doing this on all the patterns in a script or function, turn on the null_glob option:

setopt null_glob

This answer has bash and ksh equivalents.

Do not use print or command substitution! That generates a string consisting of the file names with spaces between them, instead of a list of strings. (See What is word splitting? Why is it important in shell programming?)


The better way: for a in *(.N); do ... ; done. The N option makes zsh deliver an empty list to for, and for will iterate zero times.

Watch out for ls *.foo(.N); when ls receives an empty argument list, it lists all files instead of none. This is why I don't like NULL_GLOB (or its bash equivalent): It changes all the globs and easily breaks calls to e.g. ls.


I think you are looking for the NULL_GLOB option:

   NULL_GLOB (-G)
          If a pattern for filename generation has no matches, delete  the
          pattern  from  the  argument list instead of reporting an error.
          Overrides NOMATCH.

Tags:

Zsh

Wildcards