Question

In my bash script running on an ubuntu machine I have the following simple loop

for f in ~/logs/*.log
do
    echo "processing $f"
done

If there are files in the directory ~/logs matching the pattern, it works as expected, i.e. I get

processing /home/foo/logs/a.log
processing /home/foo/logs/foo.log
processing /home/foo/logs/3.log

But when the dir is empty it treats ~/logs/*.log as the only item to iterate over, so I get this

processing /home/foo/logs/*.log 

How do I change this so that in this case it produces an empty iteration list and so never enters the loop?

Was it helpful?

Solution

Two ways:

Either, you can set the nullglob shell option:

shopt -s nullglob
for f in ~/logs/*.log
do
    echo "processing $f"
done

or test for the existence of a file:

for f in ~/logs/*.log
do
    [[ -f "$f" ]] || continue
    echo "processing $f"
done
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top