Simple Bash - for f in *

Consider this simple loop:

for f in *.{text,txt}; do echo $f; done

I want to echo ONLY valid file names. Using the $f variable in a script everything works great unless there aren't any files of that extension. In the case of an empty set, $f is set to *.text and the above line echos:

*.text
*.txt

rather than echoing nothing. This creates an error if you are trying to use $f for anything that is expecting an actual real file name and instead gets *.

If there are any files that match the wildcard so that it is not an empty set everything works as I would like. e.g.

123.text
456.txt
789.txt

How can I do this without the errors and without seemingly excessive complexity of first string matching $f for an asterisk?

Answers


Set the nullglob option.

$ for f in *.foo ; do echo "$f" ; done
*.foo
$ shopt -s nullglob
$ for f in *.foo ; do echo "$f" ; done
$ 

Need Your Help

How to get the screen refresh rate?

c++ windows opengl

Is this even possible? Since ive noticed v-sync doesnt work on my laptop at all, so i am building FPS limiter "manually" and now i would like to use the FPS limit the user has set to his screen.