Bash Break and Continue

Loops in a programming language, allows you to run commands multiple times till a particular condition. Even in Bash we have mainly three loops – until, while, and for. Sometimes you need to alter the flow of a loop and terminate it. Here comes the Break and Continue statement. They help you in terminating or managing the cycle of a loop. Here we will show you how you can use Break and Continue statements in Bash.

Bash Break Statement

The Bash Break statement helps in terminating the current loop and passing program control to the command that follows the terminated loop. We use it to exit from a while, until, for or select loops.

The syntax of the Break statement is: break[n]. Where [n] is an optional argument that must be greater than or equal to 1.

Let’s understand the Break statement with an example. Here is a simple program with a for loop that will iterate over a range of values from 1-20 with an increment of 2. The conditional statement in the third line will check the expression and when val=9 is true, the break statement will run and the loop will be terminated.

for val in {1..20..2}
do
  If [[ $val -eq 9 ]]
  then
     break
  else
  echo "printing {val}"
fi
done

Further, if you want to exit from a second loop or outer loop then you can use ‘break 2’. This will tell that loop too needs to be terminated.

Bash Continue

We use the Break statement to exit the entire loop when a condition is satisfied. What if you want to skip a particular block of code instead of exiting the entire loop? In such conditions, we use the Bash Continue statement. The Continue statement lets you skip the execution of a code block when the condition is satisfied or we can say that statement skips the remaining part of the code for the current iteration and passes control to the next iteration of the loop.

The syntax of the Continue statement is: continue [n]. Again [n] is an optional argument that can be greater than or equal to 1.

Let’s understand the Continue statement with an example. Here we have a simple program and in that when the current iterated item will be equal to 2, the continue statement will return to the beginning of the loop and continue with the next iteration.

i=0

while [[ $i -lt 5 ]]; do
  ((i++))
  if [[ "$i" == '2' ]]; then
    continue
  fi
  echo "No: $i"
done

echo 'Done!'

The output of this program will be as follows:

Output
No: 1 No: 3 No: 4 No: 5 Done!
bash break continue General Articles Shell Scripts TecAdmin