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:
for
Loop: Thefor
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.
while
Loop: Thewhile
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.
until
Loop: Theuntil
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.