Thursday, January 30, 2025
HomeProgrammingHow does the while command work in Linux with examples

How does the while command work in Linux with examples

The while command in Linux is used to execute a loop repeatedly as long as a specified condition evaluates to true. It is commonly used in shell script

while [ condition ]; do
# Commands to be executed
done
  • The condition is evaluated before each iteration.
  • If the condition is true, the loop executes the commands inside do and done.
  • The loop stops when the condition becomes false.

Examples

1. Basic While Loop

Print numbers from 1 to 5:

#!/bin/bash
count=1
while [ $count -le 5 ]; do
echo "Count: $count"
1
done

Output:

Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

2. Infinite While Loop

To create an infinite loop:

while true; do
echo "Press Ctrl+C to stop the loop"
sleep 2 # Wait for 2 seconds before repeating
done
  • The condition true always evaluates to true.
  • Use Ctrl+C to terminate the loop.
See also  What is the printf Format Specifier for bool in C?

3. Using While with Read (Reading a File Line by Line)

#!/bin/bash
while read line; do
echo "Line: $line"
done < file.txt
  • This reads file.txt line by line and prints each line.

4. Using While Loop with a Command Output

Printing system processes:

#!/bin/bash
while read process; do
echo "Process: $process"
done < <(ps -e)
  • The loop reads each line of the ps -e command output and prints it.
See also  How to Embed a PDF File Using HTML

5. While Loop with User Input

#!/bin/bash
while true; do
read -p "Enter a number (0 to quit): " num
if [ "$num" -eq 0 ]; then
echo "Exiting..."
break
fi
echo "You entered: $num"
done
  • The loop keeps asking for user input until 0 is entered.
See also  How do I find the size of an array in Perl?

Conclusion

  • while loops are useful for running commands repeatedly based on a condition.
  • They are widely used in automation, file processing, and interactive scripts
  1. count++ []
RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x