Enter your email address below and subscribe to our newsletter

Beginner’s Guide to Bash while Loops

Learn how to use while loop in bash though examples.

Share your love

Writing quality code itself is a trick and when you have to execute a specific various times, you don’t want to write a statement multiple times.

So how do you solve this problem? You use loops in programming, which lets you execute a specific task as per the given condition.

There are multiple types of loops and one of them is while loops. So in this tutorial, I will walk you through how you can use the while loop in bash with a set of practical examples.

How does the while loop in bash work?

To understand the workings of the while loop, you first need to understand the syntax. So here’s a basic syntax of the while loop:

while [ condition ]
do
   command1
   command2
   ...
   commandN
done

Now, let’s break down each line to understand how it works:

  • while: the keyword that initiates the while loop.
  • [condition]: it is the most important part of the loop. The condition statement. The condition is mostly related to based on a defined variable and the loop will only be executed if the condition is true.
  • do: the keyword that initiates the loop body.
  • command1, command2,..., comandN: n number of commands which will be executed till the condition is true.
  • done: it marks the end of the loop body.

Sounds complicated? Let me simplify it for you.

Let’s say you want to print something 5 times, so what you can do is define a variable and initialize its value to 1 (suppose the variable is a).

So what you can do is create a condition that the loop will be iterated till the value of the a variable is 5 and uses a counter inside the loop body which will increment the value of a in every iteration.

Here’s how it will work:

The condition is: The value of a is less or equal to 5. Initially, the value of a was defined as 1, so the condition is true, and the loop will print the statement. Right after that, there’s a counter which will increment the value of a by 1, so now the value of a=2.

Again, it will check the condition, and it will still be true as the current value of a (which is 2) is still less or equal to 5, so the loop will be iterated, the print statement will be executed, and the counter will increase the value of a by 1 resulting the value of the a becomes 3.

The loop will work till continues to execute the print statement till the value of a reaches 5. After executing the print statement for the 5th time, the counter will increase the value of a to 6.

So when the condition is checked to initiate the loop will be checked, it will be false and the loop will be ended.

Now, let’s take a look at some examples of the while loop in bash.

See also: 8 Must-Have PowerToys for Boosting Your Windows Productivity

Examples of a while loop in bash

In this section, I will share 4 simple examples showing how easy it is to use the while loop in bash. Will start with the easiest ones and will increase complexity gradually (just a little, nothing to scare you out).

1. Print n numbers

By far, this is the easiest way you can understand the workings of a while loop in bash. First, let me share the code and then will come to the explanation part:

#!/bin/bash

number=1

while [ $number -le 10 ]
do
  echo $number
  ((number++))
done

The above code will print numbers from 1 to 10. Let’s take a look at how it does.

Here,

  • !/bin/bash: it is a shebang instructing the system to use the bash shell to execute the script.
  • number=1: it is a variable called a number, and it was assigned 1 as an initial value.
  • [ $number -le 10 ]: it is a condition to check if the value of the number variable is less or equal to 10.
  • echo $number: will print the value of the number variable.
  • ((number++)): will increase the value of the number variable by one in every iteration.

When you execute the above script, you can expect the following output:

while loop to print number from 1 to 10 in bash

2. Using break statement

The break statement is used to exit early from the while loop when a certain condition matches. Here’s a simple while loop with a break statement:

#!/bin/bash

number=1

while [ $number -le 10 ]
do
  echo "Number: $number"

  if [ $number -eq 7 ]; then
    echo "Reached number 7. Exiting loop..."
    break
  fi

  ((number++))
done

echo "Loop exited."

In the above script, the break statement takes an early exit once it uses the echo statement the 7th time. Let’s take a look at how it works.

  • number=1: here, the variable number is initialized at 1.
  • while [ $number -le 10 ]: the while loop will execute the loop body till the value of the number variable is less or equal to 10.
  • echo "Number: $number": a print statement to print the value of the number variable.
  • if [ $number -eq 7 ]; then: if the value of the number variable is equal to 7, then execute the upcoming statement.
  • echo "Reached number 7. Exiting loop…": if the value of the number variable is equal to 7, then it will print “Reached number 7. Exiting loop…”.
  • break: Once after printing the message found inside the if statement, it will break the while loop.
  • fi: used to end the if block.
  • ((number++)): used to increase the value of the number variable by 1 in every interaction.
  • done: closing statement of the while loop.
  • echo "Loop exited": Prints “Loop exited” at the end of the output.

Does it look too complex? Let me explain.

The loop had a condition that it would be iterated till the value of the number variable is less or equal to 10 so technically, it should execute the loop body 10 times.

But wait ✋.

There’s an if statement in the loop body to check if the value of the number variable is 7 or not. Once the value of the variable increments to 7, the condition of the if statement changes to true, and it executes the break statement to exit the loop.

Here’s the output of the script:

Using break statement in while loop bash

3. Using the continue statement

The continue statement is used to skip the current iteration and move to the next iteration. In bash scripts, it is often paired with the while loop to skip certain iterations.

Here’s a simple while loop showing how to use the continue statement to skip a specific iteration:

#!/bin/bash

number=1

while [ $number -le 10 ]
do
  if [ $number -eq 5 ]; then
    echo "Skipping number 5..."
    ((number++))
    continue
  fi

  echo "Number: $number"
  ((number++))
done

echo "Loop exited."

The above while loop will skip the 5th iteration and print the message “Skipping number 5…” instead of printing the value of the number variable. So let’s take a look at how it works:

  • number=1: the number variable initialized at 1.
  • while [ $number -le 10 ]: a while loop which will iterate the loop body till the value of the number variable will be less or equal to 10.
  • if [ $number -eq 5 ]: it is the if statement checking the value of the variable and once it matches the condition, it will execute the code inside of the if statement.
  • echo "Skipping number 5…": a print statement suggesting the if statement is about to skip the 5th iteration and instead it will print “Skipping number 5…”.
  • ((number++)): increment counter inside of the if statement which will increase the value of the variable (currently 5) to 6.
  • continue: moves to the next iteration.
  • echo "Number: $number": prints the value of the number variable.
  • ((number++)): increments the number variable by 1.
  • echo "Loop exited.": a print statement suggesting the end of the loop.

If you notice the loop, I’ve used the increment (number++) two times and that’s where the real magic happens.

There’s a while loop which is supposed to print the value of the number variable 10 times. But I wanted to skip the 5th iteration so what I did is used the if statement before the echo statement of the while loop which is responsible for printing the value of a variable.

So what happens is the while loop starts with the if statement and then there’s an echo part. This means the variable is passed through the if statement first so when the condition for the if statement is true, the value is changed before it is handed over to the echo part (the second echo in code) of the while loop.

When the value of the variable is increased to 5, it will first checked by the if statement and as the value is 5, the condition for the if statement is true and will be incremented to 6. Now, the value of the number variable is 6 and is passed to the second echo statement.

This is how you skip one or more iterations with the continue statement. If you were to execute the shown script, here’s the expected output:

Use continue statement in while loop bash

4. Read file line by line

This may not be the most practical example of reading files but definitely a great way to understand the workings of the while loop as it involves the use of the read command.

First, let me share the code:

#!/bin/bash

file="my_file.txt"

while read -r line; do
  echo "$line" 
done < "$file"

The above loop will read the contents of the my_file.txt file line-by-line. Here’s how it works:

  • file="my_file.txt": the filename my_file.txt is assigned to the file variable.
  • while read -r line: here, the while loop will be iterated till the read command reads the file line-by-line and stores every line in the line variable (one at a time).
    The -r flag is used to prevent backslashes (\) from being interpreted as escape characters within the line.
  • echo "$line": prints each line stored inside of the line variable.
  • done < "$file": it redirects the data of the file stored inside of the file variable continuously.

In simple terms, it stores lines one by one inside of the line variable and prints them one by one till there’s nothing left to read by the read command and the loop ends there.

Here’s the output of the above script (I’ve also included the output of the cat command with the file to verify the output by the script itself):

Conclusion

In this guide, I explained how you can use the while loop in the bash shell including the syntax, the workings of the while loop, and 4 practical examples with different statements.

I’ve tried giving every detail possible so you can have a clear idea of how you can use the while loop in the bash.

Feel free to leave us a comment on our social media here or here for any queries or suggestions.

Share your love
Kabir
Kabir

A tech journalist whose life revolves around networks.

Newsletter Updates

Enter your email address below and subscribe to our newsletter

Stay informed and not overwhelmed, subscribe now!