Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash for loop and glob expansion [duplicate]

Tags:

bash

Consider the following bash code:

 for f in /tmp/*.dat; do echo ${f}; done

when I run this and there is no *.dat file in /tmp the output is:

/tmp/*.dat

which is clearly not what I want. However, when there is such a file, it will print out the correct one

/tmp/foo.dat

How can I force the for loop to return 'nothing' when there is no such file in the directory. The find-command is not an option, sorry for that :/ I would like to have also a solution without testing, if *.dat is a file or not. Any solutions so far?

like image 312
hellow Avatar asked Jul 08 '15 09:07

hellow


1 Answers

This should work:

shopt -s nullglob
...

From Bash Manual

nullglob

If set, Bash allows filename patterns which match no files to expand to a null string, rather than themselves.

like image 167
Jahid Avatar answered Sep 22 '22 23:09

Jahid