linux – 与任何东西都不匹配的Glob扩展到自身,而不是什么都没有

我想迭代一个特殊类型的文件夹(如.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

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.

或者使用zsh,默认情况下启用了这个glob!

$for f in *.test; do echo "$f"; done
zsh: no matches found: *.test

相关文章

用的openwrt路由器,家里宽带申请了动态公网ip,为了方便把2...
#!/bin/bashcommand1&command2&wait从Shell脚本并行...
1.先查出MAMP下面集成的PHP版本cd/Applications/MAMP/bin/ph...
1、先输入locale-a,查看一下现在已安装的语言2、若不存在如...
BashPerlTclsyntaxdiff1.进制数表示Languagebinaryoctalhexa...
正常安装了k8s后,使用kubect工具后接的命令不能直接tab补全...