How to match nothing if a file name glob has no matches [duplicate]

送分小仙女□ 提交于 2019-12-21 07:25:30

问题


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

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

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?


回答1:


Use this to avoid the unwanted iteration:

shopt -s nullglob

From man bash:

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

See: help shopt and shopt




回答2:


This and a duplicate question both were in context of not just pathname-expansion, but also brace-expansion, and a duplicate asked for POSIX.

The compgen -G does bash --posix compatible pathname-expansion (no brace-expansion) and... you guessed it: yields nothing if there are no matches.

Therefore write a bash --posix function to do it. Brief outline: temporarily use set -f to first do brace-expansion (without pathname-expansion) via an echo, then apply compgen -G to each result for pathname-expansion. Full function left as an exercise.



来源:https://stackoverflow.com/questions/29438045/how-to-match-nothing-if-a-file-name-glob-has-no-matches

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!