Search code examples
linuxbashshellbamboo

Stop a loop process in shell scripting after some time


I have a script that looks like this, this script is checking whether my pods is in Running state or Not by redefining x on every loop.

x=$(/opt/oc get pods --selector app=${bamboo.shortPlanName} -o jsonpath='{range .items[]}{.status.phase}{"\n"}{end}')

until [ "$x" == "Running" ];
do
   sleep 5
   x=$(/opt/oc get pods --selector app=${bamboo.shortPlanName} -o jsonpath='{range .items[]}{.status.phase}{"\n"}{end}')
   echo $x
done

But, I want to modify my current script to also support timeout, I mean after 60 second of looping, then it should be stop, or after 12 times of looping, then it should be stop. Any idea how to do that?


Solution

  • bash provides a special variable SECONDS that can be used as a rough timer.

    SECONDS=0
    while (( SECONDS < 60)); do
        x=$(/opt/oc get pods --selector app=${bamboo.shortPlanName} -o jsonpath='{range .items[]}{.status.phase}{"\n"}{end}')
        if [[ $x == Running ]]; then
            break
        fi
        sleep 5
    done
    

    The expansion of SECONDS gives you not the assigned value, but the difference between the numbers of seconds since the assignment and the assigned value. The effect is like a variable whose value is incremented by 1 each second.