This method is more performant than checking existence every iteration:
set -- nonexistent-file-*
[ -e "$1" ] || shift
for filename; do
echo "$filename"
done
We use set
to expand the wildcard into the shell's argument list. Note this will overwrite any positional arguments ($1
, $2
, ...) originally passed to the script. The special argument --
makes it work even if the glob pattern would start with a +
or -
character that could conflict with other set
usages otherwise.
If the first element of the argument list does not exist, the glob didn't match anything. Unlike comparing the first result with the verbatim glob pattern, this works correctly even if the glob's first match was on a filename identical to the glob pattern.
In case of no match, the argument list contains a single element, and we shift it off, so that the argument list is now empty. Then the for
loop will not perform any iterations at all.
Otherwise, we loop over the list of arguments which the glob expanded into, using the implicit behavior of for
when there is nothing after the variable name (being equivalent to in "$@"
, iterating through all positional arguments).