问题
I want to iterate over the files in a folder of a special type (like .test
):
So I wrote a little script names for_loop
:
for f in *.test
do
echo 'This is f: '${f}
done
After (chmod +x for_loop
) I can start it with ./for_loop
.
If there are .test
-files, everthing is fine, BUT if there is no file in the folder that matches *.test
, the for-loop is still executed once. In this case the output looks like:
This is f: *.test
But I thought that if there were no files in the folder that match the glob pattern, there would be no output. Why is this not the case?
回答1:
This is the default behaviour.
to get rid of it, enable nullglob
:
shopt -s nullglob
From Greg's Wiki - nullglob:
nullglob expands non-matching globs to zero arguments, rather than to themselves.
...
Without nullglob, the glob would expand to a literal * in an empty directory, resulting in an erroneous count of 1.
Or use zsh
, which has this glob enabled by default!
$ for f in *.test; do echo "$f"; done
zsh: no matches found: *.test
来源:https://stackoverflow.com/questions/33898250/glob-that-doesnt-match-anything-expands-to-itself-rather-than-to-nothing