Open In App

while Command in Linux with Example

Last Updated : 17 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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

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

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

while Command in Linux – FAQs

What is the difference between “while” and “for” loops in Linux?

The main difference is that “while” loops evaluate a condition before each iteration, while “for” loops iterate over a predefined sequence or range.

“While” loops are more flexible, as the condition can be any valid shell expression, while “for” loops are more suitable for iterating over a known set of values.

How can I use the “while” loop to read input from the user until a specific condition is met?

You can use the “while” loop in combination with the “read” command to create a prompt-based loop, as shown in the example in the article.

The loop can continue until the user enters a specific value (e.g., “q” to quit) or until a certain condition is met (e.g., a valid number is entered).

How can I use the “while” loop to iterate over a list of files or directories?

As demonstrated in the third example, you can use the “while” loop to iterate over a list of files or directories by using the output of a command (e.g., “ls”) and passing it to the loop using a “here document”.

This allows you to perform various operations on each file or directory in the list.

Can I use variables inside the “while” loop condition?

Yes, you can use variables inside the “while” loop condition. This is a common use case, as the condition often depends on the value of a variable that changes during the loop execution.

In the examples provided, the variable $count and $var are used in the loop conditions.

What happens if the “while” loop condition is always true?

If the “while” loop condition is always true, the loop will continue indefinitely, resulting in an infinite loop.

It’s important to ensure that the loop condition has a clear exit condition, such as a counter that reaches a specific value or a user input that signals the end of the loop.

Failing to provide a proper exit condition can lead to an unresponsive script or program, which may require manual intervention to stop.

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.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads