Skip to content
Advertisement

While loop to test if files with a given pattern exist in bash

I want to check with a file loop like this, if files with a given pattern exist:

while [ ! -f "/tmp/?????-Stock.txt" ]
do
  sleep 2
done

If more files like 12aaa-Stock.txt, 34aaa-Stock.txt are present I have a message error like binary operator expected.

Advertisement

Answer

You can work around this by using a for-loop, e.g,.

DONE=no
while [ "$DONE" = no ]
do
    for name in /tmp/?????-Stock.txt
    do
        if [ -f "$name" ]
        then
             DONE=yes
             break
        fi
    done
    [ "$DONE" = no ] && sleep 2
done

As long as there are no files found, the for-loop has one item to process (the unmatched pattern). If multiple files are found, the for-loop exits immediately on the first match.

@chepner notes that I could have used break 2 (old habits die hard). That would look like this:

while :
do
    for name in /tmp/?????-Stock.txt
    do
        [ -f "$name" ] && break 2
    done
    sleep 2
done
Advertisement