While Loop in Bash
The while
loop in Bash is used to execute a block of code repeatedly as long as a specified condition evaluates to true
. It's commonly used for processing files, waiting for events, or iterating over commands.
Syntax
while [condition]; do
# Commands to execute
done
Key Points:
[condition]
is a command or test expression. As long as it evaluates totrue
(exit status0
), the loop continues.- The
do
block contains the commands to execute repeatedly. - The
done
keyword marks the end of the loop.
Basic Example: Counter
count=1
while [ $count -le 5 ]; do
echo "Count: $count"
((count++)) # Increment count
done
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Example: Reading a File Line by Line
The while
loop can process files line by line using read
:
while read -r line; do
echo "Line: $line"
done < input.txt
Explanation:
read -r line
: Reads a single line from the file.< input.txt
: Redirects the fileinput.txt
as input to the loop.
Example: Waiting for a Condition
The while
loop can pause execution until a specific condition is met:
status="pending"
while [ "$status" != "done" ]; do
echo "Waiting for completion..."
sleep 2 # Pause for 2 seconds
status="done" # Simulate status change
done
echo "Task completed!"
Example: Infinite Loop
An infinite loop runs until explicitly terminated. Use with caution!
while true; do
echo "Press Ctrl+C to stop."
sleep 1
done
Explanation:
true
: Always evaluates totrue
.- Use
Ctrl+C
to stop the script manually.
Example: Nested While Loops
You can nest while
loops for complex tasks, like printing a matrix:
rows=3
cols=3
row=1
while [ $row -le $rows ]; do
col=1
while [ $col -le $cols ]; do
echo -n "$row,$col "
((col++))
done
echo
((row++))
done
Output:
1,1 1,2 1,3 2,1 2,2 2,3 3,1 3,2 3,3
Example: Using Command Output in While Loop
You can use the output of a command in a while
loop:
ls *.txt | while read -r file; do
echo "Processing file: $file"
done
Explanation:
ls *.txt
: Lists all.txt
files.while read -r file
: Processes each filename from the command output.
Breaking and Continuing a While Loop
break
: Exits the loop immediately.continue
: Skips the rest of the current iteration and starts the next.
Example:
count=1
while [ $count -le 5 ]; do
if [ $count -eq 3 ]; then
echo "Skipping $count"
((count++))
continue
fi
if [ $count -eq 5 ]; then
echo "Breaking at $count"
break
fi
echo "Count: $count"
((count++))
done
Output:
Count: 1
Count: 2
Skipping 3
Count: 4
Breaking at 5
Common Errors to Avoid
Infinite Loops: Ensure the loop condition eventually becomes
false
. Example:count=1 while [ $count -le 5 ]; do echo $count # Missing ((count++)) causes an infinite loop done
Incorrect Test Syntax: Use square brackets
[ ]
or double brackets[[ ]]
properly.while [[ $count -lt 5 ]]; do # Correct usage done
Redirection Misuse: Be cautious when using redirection (
<
,|
). Test the loop with smaller input files to ensure correctness.
Conclusion
The while
loop is a versatile construct in Bash, suitable for repetitive tasks and real-time monitoring. By mastering its syntax and usage, you can handle complex scripting challenges efficiently.
Let me know if you need further examples or details for your post!