while - Linux
Overview
The while
command in Linux is used to execute a block of commands repeatedly as long as the given condition evaluates to true. It is a fundamental control flow statement in shell scripting that enables users to automate repetitive tasks efficiently. This command is particularly useful in scenarios where the number of iterations is not known beforehand, such as processing text until a certain pattern is no longer found.
Syntax
The basic syntax of the while
loop in a shell script is:
while [ condition ]
do
command1
command2
command3
...
done
Here, [condition]
is tested before each pass through the loop. If [condition]
evaluates to true, the command1
, command2
, command3
, etc. are executed. This process repeats until the condition returns false.
Options/Flags
The while
command does not have specific options or flags since it is not a standalone utility but part of the shell syntax. However, the behavior of the loop can be influenced by how the condition and commands within it are structured.
Examples
Basic Example
# Print numbers from 1 to 5
counter=1
while [ $counter -le 5 ]
do
echo $counter
((counter++))
done
Reading Lines from a File
# Read lines from a file
while IFS= read -r line
do
echo "$line"
done < "file.txt"
Looping Until a File Exists
# Wait until a certain file is created
while [ ! -f /tmp/ready.txt ]
do
sleep 1
done
echo "File exists!"
Common Issues
-
Infinite Loops: If the loop condition never evaluates to false, the loop will continue indefinitely. To prevent this, ensure that the loop condition is properly adjusted within the loop.
-
Syntax Errors: Missing
do
ordone
keywords can cause syntax errors. Ensure all parts of the loop are correctly typed. -
Condition Mistakes: Using incorrect condition syntax like forgetting spaces around
[
and]
in test expressions can lead to unexpected behavior.
Integration
while
loops can be combined with other commands for powerful scripting solutions. Here’s an example of a script that monitors system memory and logs when usage is high:
while true
do
usage=$(free | grep Mem | awk '{print $3/$2 * 100.0}')
if (( $(echo "$usage > 90" | bc -l) )); then
echo "High memory usage: $usage%" >> /var/log/mem_log.txt
fi
sleep 10
done
Related Commands
for
– Another loop construct used for iterating over a list of items.if
– Used to perform command based on a condition.test
or[ ]
– Evaluates a conditional expression.
Refer to the Bash manual page (man bash
) for detailed information on these and other related shell programming features.