0

I am trying to do a while loop that iterates 10 times to retry 2 consecutive commands;

Basically;

retries=10
  while ((retries > 0)); do
    if ! command; then
      if ! other_command; then
                 echo "Failed to start service - retrying ${retries}"
         else
             echo "Started service successfully"
             break
          fi
         fi
         ((retries --))
         if ((retries == 0 )); then
             echo "service failed to start!"
         fi
     done

But I cannot seem to nest it properly to get the desired result, which is; try one command, if it fails, try second command. Try these 2 commands, one after the other 10 times. If either command is successful at any time, break

0

1 Answer 1

2

You don't need to nest the ifs, break helps to avoid it. It basically follows what you described.

#! /bin/bash
retries=10
while ((retries)) ; do
    if command1 ; then
        break
    elif command2 ; then
        break
    fi
    ((--retries))
done

if ((!retries)) ; then
    echo 'Service failed to start!' >&2
fi

Tested with both commands defined as

command1 () {
    r=$((RANDOM%10))
    if ((r)) ; then
        return 1
    else
        return 0
    fi
}

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.