简体   繁体   中英

Glob that doesn't match anything expands to itself, rather than to nothing

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM