1

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.

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

You can use break 2 to exit both the for loop and the while loop. This lets you get rid of the DONE variable altogether by using while : ; do as an infinite loop.
2

You can use array to get expanded globs first and then check for # of elements:

shopt -s nullglob

while arr=(/tmp/?????-Stock.txt); [[ ${#arr[@]} -eq 0 ]]; do
   sleep 2
done

shopt -s nullglob is required to suppress glob pattern when there is no matching file for given glob pattern.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.