How to match nothing if a file name glob has no ma

2020-07-02 11:13发布

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?

标签: bash glob shopt
2条回答
混吃等死
2楼-- · 2020-07-02 11:38

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.

查看更多
疯言疯语
3楼-- · 2020-07-02 11:48

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

查看更多
登录 后发表回答