Menu
Coddy logo textTech

For Loop

Part of the Fundamentals section of Coddy's Terminal journey — lesson 71 of 82.

Sometimes you need to repeat an action multiple times. Instead of writing the same command over and over, you can use a for loop to iterate through a list of items and perform an action on each one.

Here's the basic structure of a for loop in Bash:

#!/bin/bash
for name in Alice Bob Charlie; do
    echo "Hello, $name!"
done

This script outputs a greeting for each name in the list. The variable name takes on each value in turn: first "Alice", then "Bob", then "Charlie". The do keyword marks the start of the loop body, and done ends it.

For loops are especially powerful when combined with wildcards. You can loop through all files in a directory:

#!/bin/bash
for file in *.txt; do
    echo "Processing $file"
done

This iterates through every .txt file in the current directory. Each iteration, the file variable holds the current filename, letting you perform operations on each file automatically.

You can also loop through a range of numbers using brace expansion:

#!/bin/bash
for i in {1..5}; do
    echo "Number: $i"
done

This prints the numbers 1 through 5. For loops turn repetitive tasks into just a few lines of code, making your scripts more efficient and easier to maintain.

challenge icon

Challenge

Easy

Create a shell script called countdown.sh that uses a for loop to print a countdown from 5 to 1.

Your script should:

  1. Start with the shebang line (#!/bin/bash)
  2. Use a for loop with brace expansion to iterate through numbers 5 down to 1
  3. Print each number on its own line in the format: Countdown: [number]

Make the script executable and run it. Your output should be:

Countdown: 5
Countdown: 4
Countdown: 3
Countdown: 2
Countdown: 1

Hint: Use {5..1} to create a descending range. Inside the loop, use echo "Countdown: $i" where i is your loop variable.

Cheat sheet

A for loop allows you to iterate through a list of items and perform an action on each one.

Basic syntax:

for variable in list; do
    # commands
done

Loop through a list of values:

for name in Alice Bob Charlie; do
    echo "Hello, $name!"
done

Loop through files using wildcards:

for file in *.txt; do
    echo "Processing $file"
done

Loop through a range of numbers using brace expansion:

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

For descending ranges, reverse the order:

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

Try it yourself

Terminal
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals