Introduction
Use break and continue to control loops easily. They help you stop or skip parts of a loop without extra code.
break [n] continue [n]
for i in {1..5}; do if [[ $i -eq 3 ]]; then break fi echo $i done
for i in {1..5}; do if [[ $i -eq 3 ]]; then continue fi echo $i done
while true; do read -p "Enter yes or no: " answer if [[ $answer == "yes" ]]; then break elif [[ $answer == "no" ]]; then continue fi echo "Please answer yes or no." done
#!/bin/bash for i in {1..5}; do if [[ $i -eq 4 ]]; then echo "Reached 4, breaking the loop." break fi if [[ $i -eq 2 ]]; then echo "Skipping 2" continue fi echo "Number: $i" done
break command do inside a bash loop?break in loopsbreak command immediately stops the loop and exits it, no matter where it is in the loop.continue skips to the next iteration, but break stops the loop entirely.break stops loop = D [OK]for loop?continue is used to skip the current iteration and move to the next one.break stops the loop, skip and next are not valid bash commands.for i in 1 2 3 4 5; do
if [ "$i" -eq 3 ]; then
break
fi
echo $i
donei equals 3, the break command stops the loop immediately.i is 3, loop breaks, so 3 is not printed.for i in 1 2 3 4; do
if [ $i -eq 2 ]
continue
fi
echo $i
doneif statement requires a then keyword after the condition before commands.then after [ $i -eq 2 ], causing syntax error.Pass the test and this pattern moves unknown