Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

glob

shopt

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?

like image 370
John Threepwood Avatar asked Apr 03 '15 18:04

John Threepwood


1 Answers

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

like image 98
Cyrus Avatar answered Nov 04 '22 01:11

Cyrus