Limit bash while loop to 10 retries

前端 未结 4 1317
滥情空心
滥情空心 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 07:48

    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
    
    0 讨论(0)
  • 2021-01-12 07:58

    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
    
    0 讨论(0)
  • 2021-01-12 08:01

    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?

    0 讨论(0)
  • 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".

    0 讨论(0)
提交回复
热议问题