bash在文件掩码上循环 [英] bash loop over file mask

查看:56
本文介绍了bash在文件掩码上循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在文件掩码上进行for循环的正确方法是什么?

What's the proper way to do a for loop over a file mask?

例如如果掩码没有扩展到任何文件,则该循环不应运行;否则,它应该在它扩展到的所有文件上运行.

E.g. if the mask doesn't expand to any file, then the loop should not run; else, it should run over all the files that it expands to.

天真的方法的问题在于,如果*不能扩展为任何内容,则整个循环将运行一次,就好像*部分是文件名的实际部分(不包含文件名的文件) t实际上存在).

The problem with naive approach is that if the * doesn't expand to anything, then the whole loop will run once as if the * part is an actual part of a filename (of a file that doesn't actually exist).

推荐答案

一种方法是:

for f in abc*; do if [[ -f "$f" ]]; then
  # Do something with "$f"
fi; done

这也会从目录中过滤出目录,目录可能不是您想要的.

That will also filter directories out of the list, which might or might not be what you want.

如果要保留目录,请使用-e而不是-f.

If you want to keep directories, use -e instead of -f.

另一种方法是设置shell选项nullglob(可能并非在所有bash版本上都可用).设置nullglob时,与任何文件名都不匹配的模式将不会产生任何结果,而不会被更改.

Another way to do it is to set the shell option nullglob (may not be available on all bash versions). With nullglob set, patterns which don't match any filename will result in nothing instead of being unaltered.

shopt -s nullglob
for f in abc*; do
  # do something with $f
done
shopt -u nullglob

(这会在for循环的持续时间内保留nullglob的设置.您可以在循环内取消设置它,而不必等待结束,而在每个循环上执行shopt -u的开销很小.)

(That leaves nullglob set for the duration of the for loop. You can unset it inside the loop instead of waiting for the end, at the smallish cost of executing the shopt -u on every loop.)

这篇关于bash在文件掩码上循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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