letsc
letsc

Reputation: 2567

Bash : Retries in a loop

I have a bash script that sets up a bunch of config files and end with the block

sudo stop myapp
sleep 10
sudo start myapp

This enables me to go to localhost:3001 and use the UI. However for some reason the app sometimes dsnt start do I want to wrap it in a loop of sort. This is what I did:

set -xe

restart_app () {
        sudo stop myapp
        sleep 10
        sudo start myapp
}
restart_app

for i in {1..10};
do
        status=$(curl -Is localhost:3001 | head -1 | awk '{print $2}') # returns 200
        if [ -z "$status" ];then
                restart_myapp
        else
                :
        fi
done

status returns 200 if the app is up. It returns nothing if it isnt. However my script dsnt exit at all and simply goes on for 10 tries.

Upvotes: 0

Views: 244

Answers (1)

anubhava
anubhava

Reputation: 785128

However my script dsnt exit at all and simply goes on for 10 tries.

You need to break out of for loop in else:

for i in {1..10};
do
        status=$(curl -Is localhost:3001 | awk 'NR==1{print $2; exit}')
        if [[ -z "$status" ]];then
                restart_myapp
        else
                break
        fi
done

Also head is unnecessary here since awk can have condition NR==1 for first record.

Upvotes: 2

Related Questions