Sling Academy
Home/DevOps/How to use ‘do-while’ loop in Bash scripting

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

Last updated: January 28, 2024

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.

Next Article: Ubuntu: How to Ping a Remote Server/IP Address

Previous Article: How to Use ‘for’ Loop in Bash Scripting

Series: Linux Tutorials

DevOps

You May Also Like

  • How to reset Ubuntu to factory settings (4 approaches)
  • Making GET requests with cURL: A practical guide (with examples)
  • Git: What is .DS_Store and should you ignore it?
  • NGINX underscores_in_headers: Explained with examples
  • How to use Jenkins CI with private GitHub repositories
  • Terraform: Understanding State and State Files (with Examples)
  • SHA1, SHA256, and SHA512 in Terraform: A Practical Guide
  • CSRF Protection in Jenkins: An In-depth Guide (with examples)
  • Terraform: How to Merge 2 Maps
  • Terraform: How to extract filename/extension from a path
  • JSON encoding/decoding in Terraform: Explained with examples
  • Sorting Lists in Terraform: A Practical Guide
  • Terraform: How to trigger a Lambda function on resource creation
  • How to use Terraform templates
  • Understanding terraform_remote_state data source: Explained with examples
  • Jenkins Authorization: A Practical Guide (with examples)
  • Solving Jenkins Pipeline NotSerializableException: groovy.json.internal.LazyMap
  • Understanding Artifacts in Jenkins: A Practical Guide (with examples)
  • Using Jenkins with AWS EC2 and S3: A Practical Guide