我想迭代一个特殊类型的文件夹(如.test)中的文件:
所以我写了一个小脚本名称for_loop:
for f in *.test
do
echo 'This is f: '${f}
done
之后(chmod x for_loop)我可以用./for_loop启动它.
如果有.test文件,那么everthing就可以了,但是如果文件夹中没有与..test匹配的文件,for循环仍然执行一次.在这种情况下,输出看起来像:
This is f: *.test
但我认为如果文件夹中没有与glob模式匹配的文件,则没有输出.为什么不是这样?
解决方法:
这是默认行为.
要摆脱它,启用nullglob:
shopt -s 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.
或者使用zsh,默认情况下启用了这个glob!
$for f in *.test; do echo "$f"; done
zsh: no matches found: *.test