Simple Bash - for f in *

Consider this simple loop:

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

I want to send ONLY valid file names. Using the $ f variable in a script all works fine if there are no files of this extension. In the case of an empty set, $ f is set to * .text and the above echos lines:

 *.text *.txt 

instead of not repeating anything. This creates an error if you try to use $ f for everything that expects the actual file name, and instead gets *.

If there are files matching a wildcard, so this is not an empty set, everything works as we would like. eg.

 123.text 456.txt 789.txt 

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

+6
source share
3 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 $ 
+13
source

You can check if the file really exists:

 for f in *.{text,txt}; do if [ -f $f ]; then echo $f; fi; done 

or you can use the find :

 for f in $(find -name '*.text' -o -name '*.txt'); do echo $f done 
+3
source

Also, if you can afford the external use of ls , you can avoid its results by using

 for f in `ls *.txt *.text`; 
0
source

Source: https://habr.com/ru/post/924861/


All Articles