Zsh – How to Use Parameter Substitution in Glob Pattern

globzsh

I want to process a bunch of files ending in some suffixes, so I wrote the following zsh script but it did not work.

EXT=(.jpg .png .gif)
EXT=${(j.|.)EXT}    # EXT becomes '.jpg|.png|.gif'
for f in *($EXT); do     # should become '*(.jpg|.png|.gif)' but failed
    process-one-file $f
done

Why doesn't it work? How can I mix parameter substitution and glob pattern?

Best Answer

It does not work because in zsh, globbing is not done by default upon variable expansion. That why in zsh you can do:

rm -- $file

While in other shells, you need:

rm -- "$file"

If you do want globbing, you need to ask for it explicitly as in:

rm -- $~file_pattern

In your case:

for f (*($~EXT)) process-one-file $f

(note that by convention, we tend to use uppercase variable names for environment variables)

Related Question