while Command in Linux with Example
Last Updated :
17 Apr, 2024
The “while” command is a powerful tool in the Linux shell that allows you to execute a series of commands repeatedly based on a given condition. It is commonly used in shell scripts to create loops, where a block of code is executed as long as a particular condition remains true.
Basic Syntax of While Command
The basic syntax of the “while” command is as follows:
Syntax:
while [condition]
do
# commands to be executed
done
Here, “condition” in the “while” loop is evaluated before each iteration of the loop. If the condition is true, the commands inside the “do” and “done” block are executed. The loop continues until the condition becomes false.
Conditional Expressions
Numerical Comparison:
The numerical comparison operators used in the “while” loop condition are:
-eq
: Equal to
-ne
: Not equal to
-gt
: Greater than
-ge
: Greater than or equal to
-lt
: Less than
-le
: Less than or equal to
Example:Â
while [ $var -lt 10 ]
- This loop will continue as long as the value of the variableÂ
$var
 is less than 10.
String Comparison:
The string comparison operators used in the “while” loop condition are:
=
: Equal to
!=
: Not equal to
Example:Â
while [ "$var" != "stop" ]
- This loop will continue as long as the value of the variableÂ
$var
 is not equal to the string “stop”.
It’s important to use double quotes around the variable to ensure that it is properly evaluated, even if it contains spaces or other special characters.
File Existence:
The file existence operators used in the “while” loop condition are:
-f
: File exists and is a regular file
-d
: File exists and is a directory
-e
: File exists (regardless of type)
Example:Â
while [ -f "/path/to/file" ]
- This loop will continue as long as the file “/path/to/file” exists and is a regular file.
Command Execution:
You can also use the output of a command as the condition for a “while” loop.
Example:Â
while grep -q "pattern" file.txt
- This loop will continue as long as theÂ
grep
 command finds the specified “pattern” in the file “file.txt”.
The -q
 option in the grep
 command makes it “quiet”, meaning it will only return a success or failure exit status, without printing any output.
These are just a few examples of the common conditional expressions that can be used in a “while” loop. The shell supports a wide range of operators and expressions that can be used to create more complex and flexible loop conditions.
Example of while Command in Linux
Basic Usage
Let’s start with a basic example. Suppose we want to print numbers from 1 to 5 using a ‘while’ loop:

In this script, the variable ‘i’ is initialized to 1. The loop iterates as long as ‘i’ is less than or equal to 5. Within each iteration, the value of ‘i’ is echoed, and then ‘i’ is incremented
Reading Input
The ‘while’ loop is commonly used to read input from a file line by line or from the standard input. Here’s an example that reads lines from a file named ‘input.txt’:
#!/bin/bash
while IFS= read -r line
do
echo “Line: $line”
done < input.txt

reading input using while
In this script, ‘IFS=’ is used to prevent leading/trailing whitespace from being trimmed in ‘line’, and ‘-r’ is used to handle backslashes properly. The ‘while’ loop reads each line from ‘input.txt’ and echoes it.
Infinite Loop
You can create an infinite loop using ‘while true’. For instance, the following script continuously prints the current date and time:
#!/bin/bash
while true
do
date
sleep 1
done

Infinity Loop with while
This script prints the date every second indefinitely until it’s interrupted manually (e.g., using Ctrl+C).
Option help while :
It displays help information.
help while

Conclusion
In this article we discussed he “while” command which is a very useful tool in the Linux shell. It allows you to repeatedly run a set of commands as long as a certain condition is true. You can use it to count numbers, read user input, go through a list of files, and more. The condition in the “while” loop can be based on numbers, strings, files, or the output of commands. Just be careful to make sure the condition will eventually become false, or else your loop will run forever! By understanding how to use the “while” command, you can automate all kinds of tasks and make your Linux scripts much more powerful.
Similar Reads
w command in Linux with Examples
The 'w' command in Linux gives us important information about who is currently using the computer, how much the computer is being used, and what programs are running. It's a handy tool for people who take care of computer systems, as it helps them keep an eye on what users are doing, how much of the
3 min read
wall command in Linux with Examples
wall command in Linux system is used to write a message to all users. This command displays a message, or the contents of a file, or otherwise its standard input, on the terminals of all currently logged in users. The lines which will be longer than 79 characters, wrapped by this command. Short line
3 min read
watch command in Linux with Examples
The 'watch' command in Linux is a powerful utility that allows you to execute a command periodically, displaying its output in fullscreen mode. It is particularly useful for monitoring the output of commands that change over time, such as system resource usage or server status. By default, 'watch' r
4 min read
wc command in Linux with examples
wc stands for word count. As the name implies, it is mainly used for counting purpose. It is used to find out number of lines, word count, byte and characters count in the files specified in the file arguments.By default it displays four-columnar output.First column shows number of lines present in
6 min read
Wget Command in Linux/Unix
Wget is the non-interactive network downloader which is used to download files from the server even when the user has not logged on to the system and it can work in the background without hindering the current process. GNU wget is a free utility for non-interactive download of files from the Web. It
6 min read
whatis Command in Linux with Examples
whatis command in Linux is used to get a one-line manual page description. In Linux, each manual page has some sort of description within it. So, this command search for the manual pages names and show the manual page description of the specified filename or argument. Syntax of the `whatis` command
5 min read
How to Display Path of an Executable File in Linux | Which Command
In Linux finding the exact path of an excutable file can be crucial for the system adminstration, scripting and as well for troubleshooting. The `which` command helps with providing a simple and effective way to locate the executable files within the directories that are listed in your system. In th
6 min read
while Command in Linux with Example
The "while" command is a powerful tool in the Linux shell that allows you to execute a series of commands repeatedly based on a given condition. It is commonly used in shell scripts to create loops, where a block of code is executed as long as a particular condition remains true. Basic Syntax of Whi
6 min read
How to Display the current Username in Linux | whoami Command
Imagine you're working on your computer and forget who you're logged in as. In Linux, there's a special trick called "whoami" that's like asking "Hey computer, who am I right now?" This article explains how this simple command works and helps you remember who's in charge! Don't worry, it won't be fu
5 min read
write command in Linux with Examples
The `write` command in Linux facilitates the users in sending the messages directly to other logged-in users' terminals. For using this command, try on to type `write username` and then type your message. After typing your message, press `Ctrl+D` to end the session. This command is useful for quick
6 min read