4

I have following shell script.

 OUTPUT=$(systemctl is-active etcd)
 if [[ $OUTPUT == active ]]; then
       echo "The result is successfull"
   else
       echo "The result is unsuccessfull"
 fi

I want to run this script 10 times, for each time it will sleep 10 seconds. I was able to achieve this using for i in {1..10} loop and then using sleep command.

for i in {1..10}; do
   sleep 10
   OUTPUT=$(systemctl is-active etcd)
   if [[ $OUTPUT == active ]]; then
       echo "The result is successfull"
   else
       echo "The result is unsuccessfull"
   fi
done

But I want to break the script if it matches the condition during (e.g. 1st or 2nd etc) iteration and don't want to execute next iteration.

I guess I need to implement while loop, but I am not sure how can I add condition and for loop there.

2
  • I'd quote "$OUTPUT" in the if statement. It will fail if the variable is empty (and probably if it contains a space). Commented May 11, 2019 at 19:50
  • 1
    A bit off topic, but you can skip capturing the output, and just do if systemctl -q is-active etcd; then ....
    – JoL
    Commented May 11, 2019 at 20:40

1 Answer 1

7

The break builtin is used for this.

for i in {1..10}; do
   sleep 10
   OUTPUT=$(systemctl is-active etcd)
   if [[ $OUTPUT == active ]]; then
       echo "The result is successful"
       break
   else
       echo "The result is unsuccessful"
   fi
done
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .