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?
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
doesbash --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 useset -f
to first do brace-expansion (without pathname-expansion) via an echo, then applycompgen -G
to each result for pathname-expansion. Full function left as an exercise.Use this to avoid the unwanted iteration:
From
man bash
:See:
help shopt
andshopt