문제

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?

도움이 되었습니까?

해결책

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top