A while loop in bash repeatedly executes a block of commands as long as a specified condition is true. The syntax for a while loop is as follows:
while [ condition ]; do
# commands to be executed
done
Example
Here's a simple example that calculates the sum of user inputs until the user enters 0:
#!/bin/bash
sum=0
while true; do
read -p "Enter a number (0 to exit): " number
if [ "$number" -eq 0 ]; then
break
fi
sum=$((sum + number))
done
echo "The sum is: $sum"
Explanation
- Initialization: The variable
sumis initialized to0. - Condition: The loop runs indefinitely (
while true). - User Input: The user is prompted to enter a number.
- Check for Exit: If the input is
0, the loop breaks. - Sum Calculation: If the input is not
0, it adds the number tosum. - Output: After exiting the loop, the total sum is displayed.
This structure allows for flexible and repeated execution of commands based on user input or other conditions.
