Understanding Loops in Shell Scripting

In shell scripting, loops are used to execute a block of code repeatedly based on a certain condition. There are several types of loops you can use:

  1. For Loop: The for loop is used to iterate over a range of values, such as a list of items, or numbers generated by a sequence.

Syntax:

Bash
for variable in list
do
    # Code to be executed
done

Example:

Bash
for i in {1..5}
do
    echo "Number: $i"
done

This will print numbers from 1 to 5.

  1. While Loop: The while loop is used to execute a block of code as long as a specified condition is true.

Syntax:

Bash
while condition
do
    # Code to be executed
done

Example:

Bash
counter=1

while [ $counter -le 5 ]
do
    echo "Count: $counter"
    ((counter++))
 done

This will print numbers from 1 to 5.

  1. Until Loop: The until loop is similar to a while loop, but it continues to execute a block of code until the specified condition becomes true.

Syntax:

Bash
until condition
do
    # Code to be executed
done

Example:

Bash
counter=1

until [ $counter -gt 5 ]
do
    echo "Count: $counter"
    ((counter++))
done

This will print numbers from 1 to 5, just like the previous while loop example.

  1. Infinite Loop: An infinite loop is a loop that runs indefinitely until it is manually interrupted or a specific condition is met.

Syntax:

Bash
while true
do
    # Code to be executed
done

This is a basic structure for an infinite loop. You would typically include a break statement within the loop to exit it under certain conditions.

  1. Loop Control Statements:
  • break: Terminates the loop and transfers control to the next statement after the loop.
  • continue: Skips the rest of the loop code and continues with the next iteration.

Example:

Bash
for i in {1..10}
do
    if [ $i -eq 5 ]; then
       break  # Exit the loop when i is 5
     fi
     echo "Number: $i"
done

In this example, the loop will exit when i is 5.

Loops are essential for automating repetitive tasks in shell scripting. They allow you to process data, perform calculations, and execute commands multiple times, making your scripts more efficient and versatile.

Share
OpenLib .

OpenLib .

The Founder - OpenLib.io

You may also like...