For Loop in Bash: Basics and Examples

Repeat commands using classic for loops.


Bash scripting is a powerful way to automate tasks in Linux and UNIX-like systems. One staple of any programming language is the ability to repeat actions—enter the for loop. In this article, we'll explore the basics of the for loop in Bash, see its syntax, usage patterns, and go through practical examples.

What is a for Loop?

A for loop allows you to execute a set of commands repeatedly, iterating through a sequence of values. This is especially helpful when you need to manipulate groups of files, process batch jobs, or automate repetitive tasks.

Basic Syntax of for Loops in Bash

There are two primary forms of the for loop in Bash:

1. List-Based (Classic) Syntax

for VARIABLE in VALUE1 VALUE2 VALUE3; do
  commands
done
  • VARIABLE: The control variable that holds the current value in the iteration.
  • VALUE1 VALUE2 VALUE3: A list of values to iterate over.
  • commands: The block of code to execute each iteration.

Example

for color in red green blue; do
  echo "Color: $color"
done

Output:

Color: red
Color: green
Color: blue

2. C-like Syntax (Numeric Loop)

If you want to iterate over a sequence of numbers, use this familiar construct:

for (( initial; condition; increment )); do
  commands
done

Example

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

Output:

Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5

Common Use Cases

1. Looping Over Files

List all .txt files in a directory:

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

2. Processing Arguments

Iterate over command line arguments:

for arg in "$@"; do
  echo "Argument: $arg"
done

3. Reading Lines from a File

Read every line from a file:

while IFS= read -r line; do
  echo "Line: $line"
done < filename.txt

Or using a for loop with $(cat ...) (Note: less robust with spaces):

for line in $(cat filename.txt); do
  echo "Word or line: $line"
done

4. Ranges with seq

Iterate over a number range using the seq utility:

for i in $(seq 1 5); do
  echo "Counting: $i"
done

Tips and Best Practices

  • Quote variables: Always quote your variables to prevent word splitting and glob expansion: "$file", "$var".
  • Be wary with spaces: Using for x in $(cat file.txt) splits on whitespace; for line-by-line reading, prefer while read.
  • Brace Expansion: For simple numeric or alphabetic ranges, use {}:
    for i in {1..5}; do
      echo "Number: $i"
    done
    

Conclusion

The Bash for loop is a fundamental feature that can save you time and optimize your workflows. Whether you’re iterating over files, arguments, or numeric ranges, understanding these looping basics will enhance your scripting skills. Experiment with the examples above to level up your command-line automation!