</>
Skip to content
Bash lessons (13/29)

Bash — For Loops

Basic for loop

#!/bin/bash

for i in 1 2 3 4 5; do
    echo "$i"
done

Range

#!/bin/bash

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

# With step
for i in {1..10..2}; do
    echo "$i"  # 1 3 5 7 9
done

C-style for loop

#!/bin/bash

for ((i=0; i<5; i++)); do
    echo "$i"
done

Iterating files

#!/bin/bash

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

# With path
for file in /path/to/*.log; do
    echo "Log: $file"
done

Iterating arrays

#!/bin/bash

fruits=("Apple" "Banana" "Cherry")

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

# With index
for i in "${!fruits[@]}"; do
    echo "$i: ${fruits[$i]}"
done

Word splitting

#!/bin/bash

for word in This is a sentence; do
    echo "$word"
done

Mini Practice

Write Bash code that:

  1. Uses a range-based for loop
  2. Iterates over files with a glob
  3. Iterates over an array
  4. Uses a C-style for loop

Up Next

In the next lesson, you'll learn about While Loops — while and until loops.

Related Topics

Frequently Asked Questions about For Loops

What is For Loops in Bash?

For Loops is a fundamental concept in Bash. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn For Loops?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn For Loops.

Why is For Loops important in Bash?

For Loops is essential for Bash development. Understanding this concept will help you write better code and solve real-world problems more effectively.