Limit bash while loop to 10 retries

前端 未结 4 1324
滥情空心
滥情空心 2021-01-12 07:34

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/         


        
4条回答
  •  迷失自我
    2021-01-12 08:07

    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".

提交回复
热议问题