与任何事物都不匹配的Glob会自我扩展,而不是无所事事 [英] Glob that doesn't match anything expands to itself, rather than to nothing

查看:49
本文介绍了与任何事物都不匹配的Glob会自我扩展,而不是无所事事的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要遍历特殊类型(例如.test)文件夹中的文件:

I want to iterate over the files in a folder of a special type (like .test):

所以我写了一个小脚本名称for_loop:

So I wrote a little script names for_loop:

for f in *.test
do
 echo 'This is f: '${f}
done

在(chmod +x for_loop)之后,我可以从./for_loop开始.

After (chmod +x for_loop) I can start it with ./for_loop.

如果有.test个文件,一切都很好,但是,如果文件夹中没有与*.test匹配的文件,则for循环仍将执行一次.在这种情况下,输出如下所示:

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

但是我认为,如果文件夹中没有与glob模式匹配的文件,就不会有输出.为什么不是这种情况?

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?

推荐答案

这是默认行为.

要摆脱它,请启用nullglob:

shopt -s nullglob

来自 Greg的Wiki-nullglob :

nullglob将不匹配的glob扩展为零参数,而不是扩展为 自己.

nullglob expands non-matching globs to zero arguments, rather than to themselves.

...

没有nullglob,该glob会扩展为空的文字* 目录,导致错误计数为1.

Without nullglob, the glob would expand to a literal * in an empty directory, resulting in an erroneous count of 1.

或使用zsh,默认情况下已启用此glob!

Or use zsh, which has this glob enabled by default!

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

这篇关于与任何事物都不匹配的Glob会自我扩展,而不是无所事事的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆