How To Use The While Loop In Bash | Warp

Introducing Warp Factories: open, flexible infrastructure for building your own cloud software factory. Learn More

The short answer

In Bash, the while statement is a control structure used to repeat a set of instructions for as long as a specified condition remains true.

To declare a while loop, you can use the following syntax:

while [condition];
do
  # instructions
done

Where:

For example, let's consider this script used to print every digit from 1 to 9:

#!/bin/bash

x=1

while [ $x -le 9 ];
do
  echo $x
  (( x++ ))
done

Where:

Terminating the loop with the break statement

The break statement is used to immediately terminate the current loop, regardless of whether the loop's condition evaluates or not to false.

For example, let's consider this script that determines whether a number is prime:

#!/bin/bash

is_prime=true
number=3
i=2

while [ $i -lt $number ];
do
  if [[ $number -le 1 || $(($number % $i)) -eq 0 ]]; then
    is_prime=false
    break
  fi
  ((i++))
done

echo $is_prime

Where:

Skipping a loop iteration with the continue statement

The continue statement is used to skip the current iteration of a loop and directly proceed to the next iteration, without executing the remaining instructions.

For example, let's consider this script that prints all the numbers between 1 and 15 that are divisible by 3:

#!/bin/bash

number=1
max=15

while [ $number -le $max ];
do
  if [ $((number % 3)) -ne 0 ]; then
    ((number++))
    continue
  fi
  echo "$number"
  ((number++))
done

Where:

Reading from a file line by line

To read and process a text file line by line, you can combine the while loop with the read command as follows:

#!/bin/bash

file="/path/to/file"

while read -r line
do
  # instructions
done < "$file"

Where:

For example, this script reads each line of the "/var/log/apache2/access.log" file and only output the lines that contain the 192.168.2.101 IP address:

#!/bin/bash

log_file="/var/log/apache2/access.log"
ip_address="192.168.2.101"

while IFS= read -r line
do
  if [[ $line == *"$ip_address"* ]]; then
    echo "$line"
  fi
done < "$log_file"

Reading from the standard input

To read and process text from the standard input, you can combine the while loop with the read command as follows:

#!/bin/bash

while true;
do
  read input
done

Where:

For example, let's consider this script that makes a player enter a number and a second player guess that number:

#!/bin/bash

tries=0

read -p "Please enter a number: " number
echo "Got it! Clearing the screen in 3 seconds..."
sleep 3
clear

while true;
do
  read -p "Guess the number: " guess
  if [[ number -eq guess ]]; then
    echo "Great job! You guess in $tries tries."
    break
  else
    echo "Wrong number. Try again..."
    ((tries++))
  fi
done

Where:

Iterating on array elements

To iterate over the elements of an array, you can initialize an index variable to zero and use the loop condition to check if the index is less than the array's length, incrementing the index within the loop to access and process each element sequentially.

#!/bin/bash

array=(element1, ..., elementN)

index=0

while [ $index -lt ${#array[@]} ];
do
  # do something with element: ${array[$index]}
  ((index++))
done

Where:

For example, let's consider this script that outputs all the files in the current directory with a .js file extension:

#!/bin/bash

files=($(ls))
index=0

while [ $index -lt ${#files[@]} ];
do
  if [[ ${files[$index]} =~ .js$ ]]; then
    echo "${files[$index]}"
  fi
  ((index++))
done

Where:

Creating an infinite while loop

To create an infinite while loop in Bash, you must define a condition that never evaluates to false.

The most common way of doing so is to use the built-in true value as follows:

#!/bin/bash

while true;
do
  # instructions
done

Alternatively, you can also use a semicolon character (:) as follows:

#!/bin/bash

while :
do
  # instructions
done

For example, let's consider this script that simply "echoes" back into the terminal the user input until it reads the "exit" string:

#!/bin/bash

echo "Enter text (type 'exit' to quit):"

while true;
do
  read -p "> " input
  if [ "$input" == "exit" ]; then
    echo "Goodbye!"
    break
  fi
  echo "You entered: $input"
done