如果文件名glob不匹配,如何不匹配 [英] How to match nothing if a file name glob has no matches

查看:164
本文介绍了如果文件名glob不匹配,如何不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想遍历所有与扩展名jpgtxt匹配的文件.我使用:

I want to loop over all files matching extension jpg or txt. I use:

for file in myDir/*.{jpg,txt}
do
  echo "$file"
done

问题::如果目录中根本不包含jpg文件,则循环将进行一次迭代,输出为myDir/*.jpg.我认为*将被任意文件替换(如果不存在文件,则无法扩展).如何避免不必要的迭代?

Problem: If the directory contains no jpg file at all, the loop will have one iteration with output myDir/*.jpg. I thought * will be replaced by an arbitrary file (and if no file exists it cannot be expanded). How can I avoid the unwanted iteration?

推荐答案

使用它来避免不必要的迭代:

Use this to avoid the unwanted iteration:

shopt -s nullglob

来自man bash:

nullglob:如果设置了bash,则bash允许不匹配任何文件的模式(请参见上面的路径名扩展)扩展为空字符串,而不是扩展为它们自己.

nullglob: If set, bash allows patterns which match no files (see Pathname Expansion above) to expand to a null string, rather than themselves.

请参阅:help shoptshopt

这篇关于如果文件名glob不匹配,如何不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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