How to match nothing if a file name glob has no matches

3.8k Views Asked by At

I want to loop over all files matching extension jpg or txt. I use:

for file in myDir/*.{jpg,txt}
do
  echo "$file"
done

Problem: If the directory contains no jpg file at all, the loop will have one iteration with output myDir/*.jpg. I thought * will be replaced by an arbitrary file (and if no file exists it cannot be expanded). How can I avoid the unwanted iteration?

2

There are 2 best solutions below

0
On

This and a duplicate question both were in context of not just pathname-expansion, but also brace-expansion, and a duplicate asked for POSIX.

The compgen -G does bash --posix compatible pathname-expansion (no brace-expansion) and... you guessed it: yields nothing if there are no matches.

Therefore write a bash --posix function to do it. Brief outline: temporarily use set -f to first do brace-expansion (without pathname-expansion) via an echo, then apply compgen -G to each result for pathname-expansion. Full function left as an exercise.

0
On

Use this to avoid the unwanted iteration:

shopt -s nullglob

From man bash:

nullglob: If set, bash allows patterns which match no files (see Pathname Expansion above) to expand to a null string, rather than themselves.

See: help shopt and shopt