Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
While Loop
2.1.
Syntax of While Loop
3.
Boolean Operators 
4.
Implementing a While Loop
5.
Infinite While Loop
6.
Frequently Asked Questions
6.1.
What distinguishes a shell script's for loop from a while loop?
6.2.
How should we choose between a while and an until loop?
6.3.
Are do-while and a while loop equivalent?
7.
Conclusion
Last Updated: Mar 27, 2024
Easy

Shell Scripting - While Loop

Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

When we start any programming language, the “while loop” is the most basic topic we come across. We use the while loops consistently for reading files, evaluating conditions etc.

shell scripting while loop

This article will discuss while loop in shell scripting. We will first discuss the while loop’s syntax. Afterwards, we will see about boolean operators used for conditions. At last, we will implement a while loop with a limit and an infinite loop. 

So without any further ado, let’s get started.

While Loop

A while loop is used in shell scripts to execute commands until the loop's condition is repeatedly satisfied. Since we use loops to automate repetitive operations, there are several use cases for them in practical applications. Let's examine several use scenarios and discover how to employ the while loop in shell scripts.

Syntax of While Loop

The syntax of the while loop in shell scripting

while [condition - should evaluate to TRUE or FALSE]
do
    command
    command
done

 

Based on the condition passed to it, the while loop operates. It might be as straightforward as watching for a variable to reach a given value, or it can be more complicated, like watching for another command's output to match the output we provided. There are several options available here. You can use something as a condition for the while loop if you can evaluate it as TRUE or FALSE.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Boolean Operators 

These are shell script-specific operators, as opposed to the boolean operators you've seen in other programming languages, such as ==, <, >, =>, =, >=, etc. The primary distinction in how these operators are used is that they can only be used with numeric data. If the value is a string, the operation will fail.

boolean operator

Implementing a While Loop

By default, a while loop has an unlimited number of repetitions. It requires an explicit condition that at some point during the execution of the code, will become false. If not, a loop would continue until an interrupt signal was sent.

#!/bin/sh
i=0
while [ $i -lt 5 ]
do
   echo $i
   i=`expr $i + 1`
done

 

Output

output of loop

 

The script above can be saved with any name and a.sh extension. You can make the file executable with the chmod command or launch it using the bash command, such as bash filename>.sh. Run chmod +x filename>.sh to make the script executable, then type./filename>.sh to launch it.

Infinite While Loop

Now that we understand how to add a condition to end the while loop let's look at how to create an infinite while loop. All we need to do is omit the conditional sentence.

This script should be saved in a separate file with the .sh extension. The same procedures as above can be used to run the shell script. You should receive the output tens of thousands of times as soon as the script is executed, which should take less than one second.

#!/bin/sh
i=0
while :
do
    echo Script ran $i times
    ((i++))
done
echo False

 

Output

output of infinite loop

Use Ctrl + C to end the script.

Frequently Asked Questions

What distinguishes a shell script's for loop from a while loop?

If the number of iterations is known in advance, using the "for" loop is more appropriate. If the number of iterations is not known ahead of time, the "while" loop should be used. If the condition in the "for" loop is missing, the loop will repeatedly execute.

How should we choose between a while and an until loop?

The primary distinction is that the while loops are intended to continue running while a condition is met and end when that condition returns false. Contrarily, until loops are intended to continue running even if the condition returns false and only end when the condition does.

Are do-while and a while loop equivalent?

The while loop and the do-while loop are extremely similar. The only distinction is that this loop looks for conditions after a statement has been checked. So, it illustrates a certain kind of exit control loop.

Conclusion

This article briefly discussed while loop in shell scripting. We started our discussion with the while loop’s syntax. Afterwards, we discussed boolean operators used for conditions. At last, we implemented the while loop within a limit and an infinite loop. 

We hope this blog has helped you enhance your knowledge about the while loop in shell scripting. If you like to learn more, you can check out our articles: 

🌐 Introduction to Linux Shell & Scripting Shell

🌐 Linux Screen Command

🌐 Shell Scripting Interview Questions

🌐 Crontab in Linux

🌐 Shell Scripting until, select, and for loop
 

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptAWS and many more! If you wish to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! 

If you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc. In that case, you must look at the problemsinterview experiences, and interview bundles for placement preparations.

Nevertheless, you may consider our paid courses to give your career an edge over others!

Do upvote our blogs if you find them helpful and engaging!

Happy Learning!

Previous article
Signals and Traps in Shell Scripts
Next article
Shell Scripting - Until, Select and For Loop
Live masterclass