How to write while loop in Bash

Aug 06, 2023#bash

In Bash, a while loop is a fundamental control structure that allows you to repeatedly execute a block of code as long as a certain condition remains true. It’s commonly used to process files, read input, validate data, or perform any task that requires iterative execution until a specific condition is met.

The syntax of a while loop in Bash is straightforward:

while [condition]
do
  # Actions to be performed while the condition is true
done

The loop will continue to execute as long as the condition evaluates to true. Once the condition becomes false, the loop terminates, and the script continues with the code following the loop.

Continue and break

You can also use continue and break statements to control over the flow of while loops, allowing you to skip certain iterations or terminate the loop based on specific conditions.

For example, let’s say you want to write a script that prints the numbers from 1 to 10, but skips the number 5 and stops at the number 8. You can use a while loop with a continue and a break statement to achieve this. Here is the code:

#!/bin/bash

# initialize a variable to store the current number
num=1

# loop until num is greater than 10
while [ $num -le 10 ]
do
  # if num is equal to 5, skip the rest of the loop and continue with the next iteration
  if [ $num -eq 5 ]; then
    num=$((num + 1))
    continue
  fi

  # print the current number
  echo $num

  # increment num by 1
  num=$((num + 1))

  # if num is equal to 9, exit the loop and break
  if [ $num -eq 9 ]; then
    break
  fi
done

# print a message after the loop is done
echo "The loop is finished."

The output of this script would skip the number 5 and the break statement stopped the loop at the number 8:

1
2
3
4
6
7
8
The loop is finished.

Infinite while loop

An infinite while loop is a type of loop that executes a block of commands repeatedly without ever stopping, unless the loop is interrupted by a break statement or a signal such as CTRL+C. There are different ways to write an infinite while loop in bash, depending on the condition you use. Here are some common methods:

#!/bin/bash

# Using the `:`, which does nothing and always returns true.
while :
do
  # commands to execute
done

# Using the `true`, which does nothing and always returns true.
while true
do
  # commands to execute
done

# Using the `false`, which does nothing and always returns false, 
# and negate it with `!` operator.
while ! false
do
  # commands to execute
done

Practical examples

Learning while loops in Bash from examples is an effective way to master this essential control structure in shell scripting. These examples demonstrate how to read files, process data, validate input, and handle repetitive tasks efficiently.

  • A while loop that reads a file line by line.
#!/bin/bash

# File to read
file="data.txt"

# Check if the file exists
if [ ! -f "$file" ]; then
  echo "File not found: $file"
  exit 1
fi

# While loop to read the file line by line
while IFS= read -r line; do
  echo "$line"
done < "$file"
  • A while loop that prints the numbers from 1 to 10.
#!/bin/bash

# initialize a variable to store the current number
num=1

# loop until num is greater than 10
while [ $num -le 10 ]
do
  # print the current number
  echo $num

  # increment num by 1
  num=$((num + 1))
done
  • A while loop that generates random numbers between 1 and 100 until it generates a number that is divisible by 7.
#!/bin/bash

# use RANDOM variable to generate a random number between 1 and 100 and store it in num
num=$((RANDOM % 100 + 1))

# loop until num is divisible by 7
while [ $((num % 7)) -ne 0 ]
do
  # print the current number
  echo $num

  # generate another random number between 1 and 100 and store it in num
  num=$((RANDOM % 100 + 1))
done

# print the final number that is divisible by 7
echo $num
  • A while loop that asks the user to enter a password and checks if it matches.
#!/bin/bash

# define the correct password as secret123
password="secret123"

# prompt the user to enter a password and store it in input
read -p "Enter your password: " input

# loop until input matches password
while [ "$input" != "$password" ]
do
  # print an error message
  echo "Wrong password. Try again."

  # prompt the user to enter another password and store it in input
  read -p "Enter your password: " input
done

# print a success message
echo "Correct password. You are logged in."
  • A while loop that calculates the factorial of a given number.
#!/bin/bash

# prompt the user to enter a positive integer and store it in n
read -p "Enter a positive integer: " n

# initialize a variable to store the factorial result as 1
factorial=1

# initialize a variable to store the current factor as n
factor=$n

# loop until factor is zero or negative
while [ $factor -gt 0 ]
do
  # multiply factorial by factor and store it in factorial
  factorial=$((factorial * factor))

  # decrement factor by 1 and store it in factor
  factor=$((factor - 1))
done

# print the factorial result
echo "The factorial of $n is $factorial."