04. Looping control flow continue, break

In cases of exceptions, where we find that we want to direct the flow of the loop back to the test condition or break out of it, we can use two commands - continue and break.

continue

The continue keyword is used to ignore the rest of the statements for that loop iteration, and go back to the test condition.

This short script breaks forces the loop to go back to the condition when $var is equal to 5. Thus, the output would print out all values up to 10 except 5.

#!/bin/bash
 
for var in {1..10}
do
  if [ $var -eq 5 ]
  then
    continue;
  fi
  echo "$var"
done
$ ./test
1
2
3
4
6
7
8
9
10

break

To break out of a loop, simply use the command break.

If there is more than one loop you want break out of, you can specify a value after the keyword.

#!/bin/bash
 
for iter in {2..4}
do
  for var in {1..10}
  do
    if [ $var -eq 5 ]
    then
      break 2;
    fi
    echo $(($iter * $var))
  done
done

This script would print out 2 4 6 8 and then break out of both loops. Can you see why?

Take your Linux skills to the next level!

Linux for Beginners

Take your Linux skills to the next level! Try Linux & UNIX

Linux for Beginners doesn't make any assumptions about your background or knowledge of Linux. You need no prior knowledge to benefit from this book. You will be guided step by step using a logical and systematic approach. As new concepts, commands, or jargon are encountered they are explained in plain language, making it easy for anyone to understand.

$ Check price
24.9924.99Amazon 4.5 logo(101+ reviews)

More Linux & UNIX resources

Aching back from coding all day?

Self-Massage Tool

Aching back from coding all day? Try Back Problems

Relieve spasms, tight muscles, trigger points and pressure points with the Body Back Buddy! This trigger point massage is designed to help you self-message any area of your body - especially those that are hard to reach. Keeping your muscles relaxes and out of contraction is importan in helping to reduce pain and prevent muscle injury.

$ Check price
29.9529.95Amazon 4.5 logo(3,443+ reviews)

More Back Problems resources

Ad