0

I have a bash script with:-

for i in *.x *.y *.z *.a *.b *.c
do
    echo "$i"
done

If there are no files matching the pattern *.y then the variable i has the value *.y. When this happens, my logic get screwed up.

How do I stop that from occurring?

1 Answers1

2

That's where you want to use the nullglob option for non-matching globs to expand to nothing as opposed to being left asis

shopt -s nullglob
for i in *.x *.y *.z *.a *.b *.c; do
  ...
done

Here, you could also do:

shopt -s nullglob
for i in *.[xyzabc]; do
  ...
done

Which would be more efficient as there's only one glob to expand. Note however that the order would be different.

Or for extensions that are not single characters:

shopt -s nullglob extglob
for i in *.@(x|y|foo|bar); do
  ...
done

See Why is nullglob not default? for more on that and alternatives with other shells.