Matching files with various extensions using for loop [duplicate]

Solution 1:

Lose the spaces; bash cares.

for file in "${arg}"/*.{txt,h,py}; do

Solution 2:

I would like to suggest 2 improvements to the proposed solution:

A. The for file in "$arg"/.{txt,h,py} will also produce "$arg"/.txt if there are no files with txt extention and that creates errors with scripts:

$ echo *.{txt,h,py}
*.txt *.h doSomething.py

To avoid that, just before the for loop, set the nullglob to remove null globs from from the list:

$ shopt -s nullglob # Sets nullglob
$ echo *.{txt,h,py}
doSomething.py
$ shopt -u nullglob # Unsets nullglob

B. If you also want to search *.txt or *.TXT or even *.TxT (i.e. ignore case), then you also need to set the nocaseglob:

$ shopt -s nullglob # Sets nullglob
$ shopt -s nocaseglob # Sets nocaseglob
$ echo *.{txt,h,py}
myFile.TxT doSomething.py
$ shopt -u nocaseglob # Unsets nocaseglob
$ shopt -u nullglob # Unsets nullglob