While Loop Fundamentals
The while construct evaluates a condition placed after the while keyword. If the condition evaluates to true, the commands within the loop body execute. After reaching the done statement, control returns to re-evaluate the condition. This cycle continues until the condition becomes false. If the condition is initially false, the loop body never executes.
Syntax Structure
while [ condition ]
do
commands
done
While loops are particularly effective for creating daemon processes, maintaining persistent applications, and handling operations requiring intervals shorter than one minute. For longer intervals, cron jobs or for loops may be more appropriate alternatives. Infinite loops should incorporate sleep or usleep commands to regulate execution frequency.
Practical Examples
Daemon Process Implementation
A daemon process runs continuously in the background. The following script monitors system load average every three seconds:
#!/bin/bash
while :
do
uptime
sleep 3
done
The : (colon) built-in always returns true, creating an infinite loop. Alternatively, while true or while [ 1 ] achieve the same result.
Note: sleep 1 pauses execution for one second, while usleep 1000000 provides microsecond-level precision, also equivalent to one second.
Countdown Timer
This example demonstrates decrementing a counter from 10 to 1:
#!/bin/bash
counter=10
while test $counter -ge 1
do
printf "%d\n" $counter
counter=$((counter - 1))
done
Arithmetic Summation
Calculating the sum of integers from 1 to 100:
#!/bin/bash
current=1
total=0
while [[ $current -le 100 ]]
do
total=$((total + current))
current=$((current + 1))
done
echo "The sum from 1 to 100 is: $total"
This iterative approach processes each number sequentially. For better performance with large ranges, the mathematical formula sum = n * (n + 1) / 2 provides an O(1) solution.