Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit bash while loop to 10 retries

Tags:

bash

How can this while loop be limited to maximum 10 retries?

#!/bin/sh
while ! test -d /somemount/share/folder
do
    echo "Waiting for mount /somemount/share/folder..."
    sleep 1
done
like image 973
fredrik Avatar asked Nov 28 '14 14:11

fredrik


People also ask

How do you break out of a for loop in bash?

Bash break Statement The Bash break statements always apply to loops. The integer value is optional, and it is 1 by default. The number defines the depth of the break for nested loops. Therefore, to break from a nested for loop, use break 2 .

How to do retry in shell script?

Bash Script#!/bin/bash RETRY_NUM=3 RETRY_EVERY=10 NUM=$RETRY_NUM until false do 1>&2 echo failure ... retrying $NUM more times sleep $RETRY_EVERY ((NUM--)) if [ $NUM -eq 0 ] then 1>&2 echo command was not successful after $RETRY_NUM tries exit 1 fi done echo success!


1 Answers

You can also use a for loop and exit it on success:

for try in {1..10} ; do
    [[ -d /somemount/share/folder ]] && break
done

The problem (which exists in the other solutions, too) is that once the loop ends, you don't know how it ended - was the directory found, or was the counter exhausted?

like image 53
choroba Avatar answered Sep 19 '22 18:09

choroba