Here are a few examples of while loops in shell scripts:
Example 1: Counting from 1 to 10
count=1
while [ $count -le 10 ]
do
echo $count
count=$((count+1))
done
This script initializes a variable called count
to 1 and then uses a while loop to print the value of count
and increment it by 1 until it reaches 10.
Example 2: Reading lines from a file
while read line
do
echo $line
done < file.txt
This script uses a while loop to read lines from a file called file.txt
and print each line to the terminal.
Example 3: Generating random numbers
while true
do
random_number=$RANDOM
echo $random_number
sleep 1
done
This script uses a while loop to generate a new random number using the built-in $RANDOM
variable and print it to the terminal every second.
In each of these examples, the while loop continues to execute as long as the condition in the while
statement is true. When the condition becomes false, the loop terminates and the script continues to execute the next command after the done
keyword.