The while Loop in Shell Scripts

Filed Under: UNIX/Linux
While Loop

Today we’ll learn about the while loop in shell scripts. Loops are an essential part of any programming language. When we write a code to execute a set of statements 15 times, writing the same statement again and again would be unproductive.

Loops save programmer’s time.

One of the most commonly used loops in any programming language is the while loop. We use the while loop in shell scripts to repeat a set of statements as long as a given condition is satisfied after each iteration.

How does a while loop in shell scripts work?

The while loop in shell scripts helps you make your code efficient by reducing the amount of code you need to write.

It comes handy when you have to do something in your script over and over again. Let us understand the working of a while loop in shell scripts through its syntax:

while [ condition ] 
do 
    statement 1
    statement 2
done

Here, we have three keywords, namely while, do and done.

  • The first keyword ‘while’ indicates the beginning of the loop when we run the shell script.
  • It is followed by a condition enclosed in round brackets.
  • The keyword ‘do’ is used before the statements to be executed in the loop.
  • Each while loop consists of a condition followed by a set of commands.
  • Then we encounter the done keyword which marks the end of the loop.

Think of the do and done as opening and closing parenthesis in other programming languages

First, the condition is evaluated. If the condition is TRUE, the statements following do will be executed. This repeats until there is a point when the condition evaluates to FALSE.

Once the condition is false, the loop will be terminated.    

The important thing to keep in mind is that, like C programming, shell scripting is case sensitive. Hence, you need to be careful while using the keywords in your code.

If you’re interested in learning about conditional statments, click here to read about if-else in shell scripts.

Using while loop in shell scripts

Just reading through the theory and glancing over the syntax would not benefit you until and unless you can practically use it in your code.

Therefore, for better understanding of the concept and its practical application, check out the following example.   

While loop to print the first 5 numbers

It is always best to start with something basic. Here we will use while loop in shell scripts to print the first 5 natural numbers on our screen.

This simple script will loop while the value for the variable ‘a’ is less than (‘-lt’) the 5. The condition holds for numbers from 1 to 4, therefore, the command will be executed for the same.

For any number greater than or equal to 5, the condition is false. Hence, the loop will be terminated. Here is how the code will be written.

#!/bin/sh
a=1
while [ $a -lt 5 ]
do
    echo $a
    ((a++))
done
While Loop Iteration
While Loop Iteration

Finding the Factorial Using the while Loop in Shell Scripts

One of the more practical examples would be using the functionality of a while loop to complete a task. Let’s find the factorial of a number.

The following code shows how we can accomplish this task using the while loop.

#!/bin/sh
counter=5
factorial=1
while [ $counter -gt 0 ]
do 
      factorial=$(( $factorial * $counter ))
      ((counter--))
done 
echo $factorial
Bash Factorial While Loop in shell scripts
Bash Factorial While Loop

As you can see, the factorial for the while loop is printed correctly as 120.

Reading a File in Shell Scripts Using the while Loop

When we are dealing with text files, while loop turns out to be an important tool as we can make the loop read the entire file using the while read command.

This command can help us read the contents of a file from the command line. The following code uses this functionality of the while loop in shell script to read the contents of a file one line at a time, then print it on the user’s screen.

#!/bin/bash
FILE=$1
while read line
do
    # use $line variable to process line
    echo $line
done < $FILE
While Loop For File Reading
While Loop For File Reading

As you can see, I’ve passed the file name as an argument because in our shell script, we have used $1 and assigned it to the FILE variable. This means the first argument will be accepted as the file name and the script will proceed to read the file.

Also, we use the input redirection operator within the script after the done so we can use the filename directly as an argument when executing the script.

If you skip that part, your command will look something on the lines of:

bash file.sh < filename.txt

So you see, redirect the input within the script or while executing the script. The results are the same.

Conclusion

The while loop in shell scripts is a key weapon in every shell programmer’s arsenal. It is the best tool to use when you need to execute a set of statements repeated based on a condition.

By automating the execution of specific statements you not only need to write less code, but you also free up time which can be used in more important tasks such as debugging. 

We hope this tutorial was able to help you understand how to use the While loop function. If you have any queries, feedback or suggestions, feel free to reach out to us in the comments below.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages