Shell Script While Loop


In shell scripting, a while loop is used to repeatedly execute a block of code as long as a specified condition is true. Here's the basic syntax of a while loop:

while [ condition ]; do
    # Code to execute while the condition is true
done

Here's how it works:

  1. The condition is evaluated.
  2. If the condition is true (returns a zero exit status), the code block inside the while loop is executed.
  3. After executing the code block, the condition is evaluated again.
  4. If the condition is still true, the code block is executed again.
  5. This process repeats until the condition becomes false (returns a non-zero exit status), at which point the while loop terminates, and the script continues with the next command after the done statement.

Here's an example of a while loop that counts from 1 to 5:

#!/bin/bash

count=1
while [ $count -le 5 ]; do
    echo "Count: $count"
    ((count++))
done

In this script:

  • The count variable is initialized to 1.
  • The while loop checks whether $count is less than or equal to 5.
  • If the condition is true, it prints the value of count and increments it by 1 using ((count++)).
  • The loop continues until count is no longer less than or equal to 5.

You can also use break statements within a while loop to exit the loop prematurely based on certain conditions. Here's an example:

#!/bin/bash

count=1
while true; do
    echo "Count: $count"
    ((count++))
    
    if [ $count -gt 5 ]; then
        break  # Exit the loop when count is greater than 5
    fi
done

In this script, we use while true to create an infinite loop and then use an if statement with the break command to exit the loop when count becomes greater than 5.

While loops are useful for scenarios where you need to repeat a task until a specific condition is met, such as reading lines from a file, processing user input, or waiting for a specific event to occur.

Example

Here is a simple example which shows that loop terminates as soon as a becomes 6 −




Rs. 5.0 Rs. 10.0


Buy Now