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

不打扰是莪最后的温柔 提交于 2019-12-10 16:25:04

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!