How to repeat loop n times in Bash
There are many ways to do this loop.
With ksh93
syntax (also supported by zsh
and bash
):
for (( i=0; i<10; ++i)); do
[ -e filename ] && break
sleep 10
done
For any POSIX-like shell:
n=0
while [ "$n" -lt 10 ] && [ ! -e filename ]; do
n=$(( n + 1 ))
sleep 10
done
Both of the loops sleep 10 seconds in each iteration before testing the existence of the file again.
After the loop has finished, you will have to test for existence of the file a last time to figure out whether the loop exited due to running 10 times or due to the file appearing.
If you wish, and if you have access to inotify-tools, you may replace the sleep 10
call with
inotifywait -q -t 10 -e create ./ >/dev/null
This would wait for a file creation event to occur in the current directory, but would time out after 10 seconds. This way your loop would exit as soon as the given filename appeared (if it appeared).
The full code, with inotifywait
(replace with sleep 10
if you don't want that), may look like
for (( i=0; i<10; ++i)); do
[ -e filename ] && break
inotifywait -q -t 10 -e create ./ >/dev/null
done
if [ -e filename ]; then
echo 'file appeared!'
else
echo 'file did not turn up in time'
fi
If the count is not a variable you can use brace expansion:
for i in {1..10} # you can also use {0..9}
do
whatever
done
If the count is a variable you can use the seq
command:
count=10
for i in $(seq $count)
do
whatever
done