Bash Loops

In Bash, loops are used to iterate over a set of values or execute a block of code repeatedly until a certain condition is met. There are several types of loops available in Bash, including for loops, while loops, and until loops. Here are examples of each:

  1. for Loop: The for loop iterates over a list of values or elements. You can use it to iterate over arrays, files, or a sequence of numbers.
#!/bin/bash

# Iterate over a list of values
fruits=("apple" "banana" "orange" "grape")

for fruit in "${fruits[@]}"; do
    echo "I like $fruit."
done

# Iterate over a sequence of numbers
for ((i=1; i<=5; i++)); do
    echo "Number: $i"
done

In this example, the first for loop iterates over an array of fruits and prints a message for each fruit. The second for loop iterates over a sequence of numbers from 1 to 5 and prints the number.

  1. while Loop: The while loop repeatedly executes a block of code as long as a condition is true.
#!/bin/bash

count=1

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

In this example, the while loop prints the value of the count variable and increments it by 1 until it reaches 5.

  1. until Loop: The until loop repeatedly executes a block of code as long as a condition is false.
#!/bin/bash

count=1

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

In this example, the until loop prints the value of the count variable and increments it by 1 until it becomes greater than 5.

Loops are useful for automating repetitive tasks, processing collections of data, and controlling the flow of your Bash scripts. You can choose the appropriate loop type based on your specific requirements.

Leave a Comment

Your email address will not be published. Required fields are marked *