Limit bash while loop to 10 retries

I would comment but I do not have enough points for that. I want to contribute anyway. So this makes it work even if the while loop is nested in another loop. before the break the c variable is being reset to zero. credits to @anubhava who came up with the original solution.

#!/bin/sh

while ! test -d /somemount/share/folder
do
    echo "Waiting for mount /somemount/share/folder..."
    ((c++)) && ((c==10)) && c=0 && break
    sleep 1
done

Keep a counter:

#!/bin/sh

while ! test -d /somemount/share/folder
do
    echo "Waiting for mount /somemount/share/folder..."
    ((c++)) && ((c==10)) && break
    sleep 1
done

You can use until (instead of "while ! ... break), with a counter limit:

COUNT=0
ATTEMPTS=10
until [[ -d /somemount/share/folder ]] || [[ $COUNT -eq $ATTEMPTS ]]; do
  echo -e "$(( COUNT++ ))... \c"
  sleep 1
done
[[ $COUNT -eq $ATTEMPTS ]] && echo "Could not access mount" && (exit 1)

Notes:

  • Just like setting counter as variable, you can set var condition="[[ .. ]]", and use until eval $condition to make it more generic.
  • echo $(( COUNT++ )) increases the counter while printing.

  • If running inside a function, use "return 1" instead of "exit 1".


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?

Tags:

Bash