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
anddone
. - 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.
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.
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.
Conclusion
while
loops are useful for running commands repeatedly based on a condition.- They are widely used in automation, file processing, and interactive scripts
- count++ [↩]