没有匹配的文件时如何跳过for循环? [英] How to skip the for loop when there are no matching files?

查看:134
本文介绍了没有匹配的文件时如何跳过for循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我遍历所有以foo开头的文件时,我会这样做

When I loop through all the files starting by foo I do

for f in foo* ; do echo "result = $f" ; done

问题是当没有文件foo开始时,我得到了:

The problem is when no file start by foo I get:

result = foo*

这意味着即使没有文件由foo开始,循环也会执行一次.

Meaning that the loop is executed once, even if no file start by foo.

这怎么可能?我该如何循环浏览所有文件(如果没有文件则根本不循环)?

How is this possible? How can I loop through all files (and not loop at all if there is no file)?

推荐答案

您可以通过设置 nullglob :

shopt -s nullglob

从链接页面:

nullglob是Bash shell选项,用于修改[[glob]]扩展 这样,没有文件匹配的模式会扩展为零参数, 而不是自己.

nullglob is a Bash shell option which modifies [[glob]] expansion such that patterns that match no files expand to zero arguments, rather than to themselves.

您可以使用-u删除此设置(未设置,而s用于设置):

You can remove this setting with -u (unset, whereas s is for set):

shopt -u nullglob

测试

$ touch foo1 foo2 foo3
$ for file in foo*; do echo "$file"; done
foo1
foo2
foo3
$ rm foo*

让我们看看:

$ for file in foo*; do echo "$file"; done
foo*

设置nullglob:

$ shopt -s nullglob
$ for file in foo*; do echo "$file"; done
$

然后我们禁用该行为:

$ shopt -u nullglob
$ for file in foo*; do echo "$file"; done
foo*

这篇关于没有匹配的文件时如何跳过for循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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