BudiBadu Logo
Samplebadu

Bash by Example: Loops

Bash 5.0+

Automating repetitive tasks with for, while, and until loops. Understanding the differences between condition-based loops and iteration-based loops, using brace expansion for numeric ranges, implementing loop control with break and continue statements, and choosing the right loop type for different automation scenarios.

Code

#!/bin/bash

# For loop with range
echo "Counting up:"
for i in {1..3}; do
    echo "Number: $i"
done

# While loop
echo -e "\nCountdown:"
count=3
while [ $count -gt 0 ]; do
    echo "$count..."
    ((count--))
done

# Until loop
echo -e "\nWaiting:"
n=0
until [ $n -ge 3 ]; do
    echo "n is $n"
    ((n++))
done

Explanation

Loops are fundamental for automating repetitive tasks. Bash supports several types of loops, each suited for different scenarios. The for loop is ideal for iterating over lists or ranges, while while and until loops are used when the number of iterations depends on a condition.

Here is a quick overview of the loop types:

  • For Loop: Iterates over a sequence of values (strings, files, or numbers).
  • While Loop: Continues executing as long as the condition is true.
  • Until Loop: Continues executing as long as the condition is false (until it becomes true).

Inside loops, you can use break to exit the loop immediately or continue to skip the rest of the current iteration and start the next one. These control statements provide fine-grained control over the loop's execution flow.

Code Breakdown

5
{1..3} is a brace expansion that generates the sequence "1 2 3". This is a concise way to create ranges for loops.
11
The while loop checks if $count is greater than 0. It runs as long as this condition returns true (exit status 0).
13
((count--)) decrements the variable. The double parentheses allow for C-style arithmetic operations without the $ prefix for variables.
19
The until loop is the opposite of while. It runs until the condition becomes true. Here, it stops when n is greater than or equal to 3.