How to Emulate Do-While Loop in Bash

Nilesh Katuwal Feb 02, 2024
  1. Basic Syntax of do-while Loop in Bash
  2. the break Statement in Bash
  3. the continue Statement in Bash
How to Emulate Do-While Loop in Bash

Looping is a fundamental idea in programming that will be pretty useful in multitasking tasks. We may use numerous functions such as for, while, and until to loop in bash scripting.

In this lesson, we’ll go through how to use the do-while loop in bash.

Basic Syntax of do-while Loop in Bash

The fundamental syntax for a do-while loop is as follows.

while [condition]
    do
        first command;
        second command;
        .
        .
        .
        nth command;
done

A while loop’s parameters can be any boolean expression. When the conditional never evaluates to false, the loop becomes infinite.

Hit CTRL + C to stop the infinite loop. Let’s look at an example:

#!/bin/bash
x=0
while [ $x -le 4 ]
do
  echo "The value is $x"
  ((x++))
done

The current value of the variable is printed and increased by one at each iteration in the example. The initial value of the $x variable is 0.

The script above will run till the fourth line is reached. The suffix -le denotes less than or equal to.

Output:

The value is 0
The value is 1
The value is 2
The value is 3
The value is 4

the break Statement in Bash

We use a break statement inside the loop to terminate the loop when a condition is fulfilled.

For example, the loop will terminate in the script below after the ninth iteration. We may, however, halt the looping on the fourth iteration by using break and if statements.

#!/bin/bash
x=0
while [ $x -le 9 ]
do
  echo "The value is $x"
  ((x++))
 if [[ "$x" == '4' ]];
  then  
    break  
 fi
done

Output:

The value is 0
The value is 1
The value is 2
The value is 3

the continue Statement in Bash

The continue statement quits the current loop iteration and transfers program control to the next iteration.

Let’s look at an example. When the current iterated item equals 3, the continue statement causes execution to return to the start of the loop and continue with the next iteration.

#!/bin/bash
x=0
while [ $x -le 5 ]
do
  ((x++))
 if [[ "$x" == '3' ]];
  then  
    continue  
 fi
 echo "The value is $x"
done

Output:

The value is 1
The value is 2
The value is 4
The value is 5
The value is 6

As expected in the above output, when $x equaled 3, it skipped the iteration and moved on to the next.