How does a while loop work in bash?

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

  1. Initialization: The variable sum is initialized to 0.
  2. Condition: The loop runs indefinitely (while true).
  3. User Input: The user is prompted to enter a number.
  4. Check for Exit: If the input is 0, the loop breaks.
  5. Sum Calculation: If the input is not 0, it adds the number to sum.
  6. 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.

0 Comments

no data
Be the first to share your comment!