Search code examples
bashfor-loopglob

how to stop bash from returning wildcard when pattern doesn match?


When pattern match this code work as intended:

mkdir -p mytestdir001
for f in "mytestdir???"; do
  echo $f
done

but when I replace wildcard so no item will be matched the for loop returns the wildcard.

Is there a way to prevent this other than checking in the loop if f variable is equal to initial wildcard ?


Solution

  • Set the nullglob option.

    $ shopt -s nullglob
    $ for f in *notfound ; do echo "$f" ; done
    $