Basic FOR loop with break

Oracle Linux : 6.4/bash shell

In the below I want to break out of the loop when it enters the 5th iteration.

#!/bin/bash
for i in 1 2 3 4 5 6
do
 echo "$i"
	if	[ $i -eq 5 ]
		echo "Oh Nooo... i = $i. I need to stop the iteration and jump out of the loop"
		then break
	fi
done 

But, it only iterates once. Why ?

Output:

$ ./breakTest.sh
1
Oh Nooo... i = 1. I need to stop the iteration and jump out of the loop
$
if [ $i -eq 5 ]
   then
   echo "Oh Nooo....etc"
   break
fi
1 Like

Thank you cjcox. I placed then keyword in the wrong place :slight_smile:

You can use a WHILE loop like this ...

COUNTER=0; while [  $COUNTER -lt 6 ]; do; echo "Oh Nooo... The counter is $COUNTER. I need to stop the iteration and jump out of the loop"; let COUNTER=COUNTER+1 ; done

or an UNTIL loop like this ...

COUNTER=5; until [  $COUNTER -eq 4 ]; do echo "Oh Nooo... The counter is $COUNTER. I need to stop the iteration and jump out of the loop" ; let COUNTER-=1; done