When I loop through all the files starting by foo
I do
for f in foo* ; do echo "result = $f" ; done
The problem is when no file start by foo
I get:
result = foo*
Meaning that the loop is executed once, even if no file start by foo
.
How is this possible? How can I loop through all files (and not loop at all if there is no file)?
You can stop this behaviour by setting nullglob:
From the linked page:
You can remove this setting with
-u
(unset, whereass
is for set):Test
Let's see:
Setting
nullglob
:And then we disable the behaviour:
The standard way to do this (if you can't or don't want to use
nullglob
) is to simply check if the file exists.The overhead of checking each value of
$file
is necessary because if$file
expands tofoo*
, you don't yet know if there actually was a file namedfoo*
(because it matches the pattern) or if the pattern failed to match and expanded to itself. Usingnullglob
, of course, removes that ambiguity because a failed expansion produces no arguments and the loop itself never executes the body.