How to use ‘do-while’ loop in Bash scripting

Updated: January 28, 2024 By: Guest Contributor Post a comment

Introduction

Bash scripting offers multiple ways to perform repetitive tasks, amongst which while and until loops are quite common. However, sometimes programmers from other languages like C or Java search for the do-while loop in Bash which is not directly available but can be implemented using a loop with a conditional exit. This tutorial aims to guide you on how to simulate the do-while loop in Bash scripting, which executes a block of commands once and then repeats the loop as long as a condition is true.

Understanding the Basics

Before we dive into creating a do-while loop in Bash, let’s go over the basics. A while loop will continue to execute as long as the test condition is true. A do-while differs in that it will execute the code block at least once regardless of the test condition and then continue to execute it as long as the condition is true.

In Bash, a typical while loop looks like this:

while [ condition ]
do
  # commands
done

However, to achieve do-while loop functionality, we slightly adjust this by placing the condition at the end:

do
  # commands
done
until [ condition ]

Setting up the Environment

To try out the following examples, ensure you have access to a Unix-like environment with Bash installed. You can use a Linux distribution or macOS terminal, or for Windows, you can use WSL (Windows Subsystem for Linux), Cygwin, or Git Bash.

Basic Example of a Bash ‘do-while’ Loop

Let’s look at a simple example to print the numbers from 1 to 5. Even if the ‘do-while’ loop isn’t available in Bash, we can simulate it:

#!/bin/bash

# Initialize counter
counter=1

# Do-while loop simulation
repeat=false
do
  echo "Number: $counter"
  ((counter++))
  [[ $counter -le 5 ]] && repeat=true || repeat=false
while $repeat
done

When this script is executed, it will output:

Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

This script initializes a counter and outputs it, then increments it. The condition for the repeating is placed at the end of the loop inside the while statement. It checks if we’ve reached the desired number, otherwise, it ends the loop.

Working with User Input

Now, let’s build a script where we ask for user input at least once but keep asking as long as the input is not correct.

#!/bin/bash

# Variable to store user input
input=""

# Do-while loop simulation
repeat=false
do
  read -p "Enter the secret word: " input
  [[ "$input" == "bash" ]] && break || repeat=true
while $repeat
done

echo "You have discovered the secret word!"

In this example, the loop will run at least once, asking the user for the ‘secret word’. If the user enters the word “bash”, the loop will break, otherwise, it repeats.

Advanced Usage

For more advanced usage, you might encounter situations where you need to include multiple commands or manage errors within the loop. Here’s how you might implement intermediate error-checking:

#!/bin/bash

# Function to perform complex tasks
function perform_task() {
  # Imagine this function does something complex
  # but sometimes fails. For the sake of this example,
  # it returns 1 randomly.
  return $((RANDOM % 2))
}

# Execute task till success
repeat=false
do
  perform_task
  status=$?
  if [[ $status -ne 0 ]]; then
    echo "Task failed, retrying..."
    repeat=true
  else
    echo "Task succeeded!"
    repeat=false
  fi
while $repeat
done

In this advanced example, a function perform_task simulates a task that may sometimes fail, returning a non-zero status. The loop continues until perform_task executes successfully.

Conclusion

Hopefully, this guide has given you the confidence to effectively simulate do-while loops in your Bash scripts, enhancing their logic and control flow capabilities for various scripting tasks.