Do While Loops Shell Scripting?

//

Larry Thompson

Do While Loops in Shell Scripting

A do while loop is a control flow statement that executes a block of code repeatedly as long as a specified condition is true. It is commonly used in shell scripting to automate repetitive tasks and keep the code organized. In this tutorial, we will explore the syntax and usage of do while loops in shell scripting.

Syntax

The syntax for a do while loop in shell scripting is as follows:

do
    # Code block to be executed
while condition

The code block within the do keyword will be executed first, and then the condition will be checked. If the condition evaluates to true, the code block will be executed again. This process continues until the condition becomes false.

Example

Let’s see an example to understand how do while loops work in shell scripting:

#!/bin/bash

counter=1

do
    echo "Counter: $counter"
    ((counter++))
done while ((counter <= 5))

In this example, we start with a variable counter initialized to 1. The code block within the loop prints the value of counter using echo, and then increments it by 1 using ((counter++)).

The condition for this loop is ((counter <= 5)). As long as counter is less than or equal to 5, the loop will continue executing.

  • If counter = 1: The code block is executed, and the value of counter is printed as “Counter: 1”.
  • If counter = 2: The code block is executed again, and the value of counter is printed as “Counter: 2”.
  • If counter = 3: The code block is executed again, and the value of counter is printed as “Counter: 3”.
  • If counter = 4: The code block is executed again, and the value of counter is printed as “Counter: 4”.
  • If counter = 5: The code block is executed again, and the value of counter is printed as “Counter: 5”.
  • After this point, since the condition becomes false (counter > 5), the loop stops executing.

The output of running this script will be:

Counter: 1
Counter: 2
Counter: 3
Counter: 4
Counter: 5

Conclusion

Do while loops are a powerful tool in shell scripting that allow you to repeat a block of code until a specific condition becomes false. They are useful for automating repetitive tasks and iterating over collections or files.

In this tutorial, we learned about the syntax and usage of do while loops in shell scripting. We explored an example to demonstrate how they work in practice. By incorporating do while loops into your shell scripts, you can enhance their functionality and make them more efficient.