Flow Control in Linux: Mastering For Loops for Beginners

Discover the essentials of flow control in Linux with for loops in this beginner-friendly article. Learn how to automate tasks using traditional and C-style for loops, complete with practical examples and best practices for scripting. Perfect for those new to Linux programming!
code
linux
Author

Steven P. Sanderson II, MPH

Published

April 25, 2025

Keywords

Programming, flow control, for loops, bash scripting, looping constructs in Linux, traditional shell for loop, C-style for loop examples, automate tasks in Linux, bash loop examples, shell scripting techniques, bash for loop syntax, how to use for loops in bash scripting, beginners guide to flow control in Linux, examples of C-style for loops in Linux, automating tasks with bash for loops, traditional and modern for loop syntax in bash

Key Takeaway: For loops in Linux come in two main forms: the traditional shell form for iterating through lists, and the C language form for numeric sequences. Both provide powerful ways to automate repetitive tasks in your scripts with minimal code.

Author’s Note: Hello, readers! I am currently learning as I write this series, so I might make some mistakes. I encourage you to comment on your experiences and let me know if you spot any errors. Your feedback will help me improve and provide better content for everyone.

Introduction

For loops are essential tools for Linux programmers that allow you to execute commands repeatedly with different values. Whether you’re processing files, counting through sequences, or automating repetitive tasks, understanding for loops will significantly improve your scripting abilities. This guide breaks down the basics of for loops in Linux with simple, working examples perfect for beginners.

What Is a For Loop?

A for loop is a programming construct that repeats a block of code for a specified number of iterations. In Linux bash scripting, for loops come in two main forms:

  1. Traditional Shell Form - Used mainly for iterating through lists of items
  2. C Language Form - Used mainly for numeric sequences

Let’s explore both forms with practical examples that you can try yourself.


Basic Syntax of For Loops

Loop Syntax Comparison

Type Syntax Example Use Case
Traditional for var in list for i in A B C; do echo $i; done List iteration
C-style for ((expr;expr;expr)) for ((i=0;i<5;i++)); do echo $i; done Counter loops
Range for var in {x..y} for i in {1..5}; do echo $i; done Sequences
Command for var in $(cmd) for i in $(ls); do echo $i; done Command output

Traditional Shell Form: The Basics

The traditional shell form follows this syntax:

for variable in words; do
    commands
done

Here, variable takes on each value from the words list, one at a time, and the commands between do and done are executed for each value.

Example 1: Simple List Iteration

#!/bin/bash
for i in A B C D; do 
    echo $i
done

Output:

A
B
C
D

In this example, the variable i takes on the values A, B, C, and D in sequence, and the echo $i command prints each value on a new line.


Different Ways to Create Lists

You can create lists for your for loops in several ways:

Example 2: Using Brace Expansion

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

Output:

Number 1
Number 2
Number 3
Number 4
Number 5

Brace expansion creates a sequence from 1 to 5, providing a convenient way to iterate through ranges.

Example 3: Using Pathname Expansion

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

Output from my terminal:

Processing read_integer.txt
Processing test_file.txt

This script will find all files with a .txt extension in the current directory and print a message for each one. This is incredibly useful for batch file processing.

Example 4: Using Command Substitution

#!/bin/bash
for user in $(cat /etc/passwd | cut -d: -f1); do
    echo "User: $user"
done

This example uses command substitution to iterate through the list of usernames from the /etc/passwd file. The $(command) syntax executes the command and uses its output as the list.


C Language Form For Loops

The C language form of for loops follows a syntax similar to C programming:

for ((expression1; expression2; expression3)); do
    commands
done
  • expression1: Initialization (executed before the loop starts)
  • expression2: Condition (checked before each iteration)
  • expression3: Modification (executed after each iteration)

Example 5: Basic Counter

#!/bin/bash
for ((i=0; i<5; i++)); do
    echo "Index $i"
done

Output:

Index 0
Index 1
Index 2
Index 3
Index 4

This loop initializes i to 0, continues as long as i is less than 5, and increments i by 1 after each iteration.


Common Use Cases and Examples

Common Use Cases and Examples

Task Syntax Example Description
File Processing for f in *.txt; do echo $f; done Process text files
Number Sequence for i in {1..10}; do echo $i; done Count from 1 to 10
Array Iteration for item in ${array[@]}; do… Process array items
Directory Scan for d in */; do echo $d; done List directories

Example 6: Batch File Renaming

#!/bin/bash
count=1
for file in *.jpg; do
    mv "$file" "image_$count.jpg"
    ((count++))
done

This script renames all JPEG files in the current directory to “image_1.jpg”, “image_2.jpg”, and so on.

Example 7: Creating Multiple Directories

#!/bin/bash
for name in project1 project2 project3; do
    mkdir -p "$name"
    echo "Created directory: $name"
done

This script creates three directories named “project1”, “project2”, and “project3”.


Advanced Techniques: Nested Loops

For more complex tasks, you can nest one for loop inside another:

#!/bin/bash
for i in {1..3}; do
    for j in {1..3}; do
        echo "Position $i,$j"
    done
done

Output:

Position 1,1
Position 1,2
Position 1,3
Position 2,1
Position 2,2
Position 2,3
Position 3,1
Position 3,2
Position 3,3

Nested loops are useful for tasks involving grid-like data structures or when you need to process combinations of items.


Best Practices for Using For Loops

Best Practices Summary

Practice Description Example
Quote Variables Always quote variables to prevent word splitting for i in “$var”
Meaningful Names Use descriptive variable names for file in *.txt
Indentation Indent loop body for readability echo $item
Error Checking Include error handling in loops if [ -f “$file” ]

Tips for Effective For Loops:

  1. Use meaningful variable names: While i, j, and k are traditional variables for loops (inherited from Fortran), using descriptive names like file, user, or item makes your code more readable.

  2. Always quote your variables: To prevent issues with filenames or values containing spaces, always quote your variables:

    for file in *.txt; do
        cat "$file"  # Quotes prevent issues with spaces
    done
  3. Check for errors within loops: Add error checking inside your loops:

    for file in *.txt; do
        if [ -f "$file" ]; then
            echo "Processing $file"
        else
            echo "Error: $file is not a regular file"
        fi
    done
  4. Use indentation consistently: Proper indentation improves readability and helps identify the loop structure.


Time Savings Through Automation

One of the most significant benefits of mastering for loops is the time savings they provide:

Task Time Without Automation Time With Automation
Renaming files 3 hours 5 minutes
Data processing 2 hours 10 minutes
Error rate 10% 1%

Example: Reporting Disk Space in Home Directories

This practical example uses a for loop to measure disk space usage—for all users (if you’re the root user) or just for the current user. It also prints a table for clarity.

#!/bin/bash
# report_home_space: Reports disk space usage for home directories

# Define the table format using printf notation
format="%8s%10s%10s\n"

# Set the directory list and user name based on privileges
if [[ $(id -u) -eq 0 ]]; then
    dir_list="/home/*"
    user_name="All Users"
else
    dir_list="$HOME"
    user_name="$USER"
fi

echo "<H2>Home Space Utilization for $user_name</H2>"

# Loop through each directory in the list
for dir in $dir_list; do
    total_files=$(find "$dir" -type f 2>/dev/null | wc -l)
    total_dirs=$(find "$dir" -type d 2>/dev/null | wc -l)
    total_size=$(du -sh "$dir" 2>/dev/null | cut -f1)
    
    echo "<H3>$dir</H3>"
    echo "<PRE>"
    printf "$format" "Dirs" "Files" "Size"
    printf "$format" "----" "-----" "----"
    printf "$format" "$total_dirs" "$total_files" "$total_size"
    echo "</PRE>"
done

Explanation:

  • The script checks if the current user is root.
  • If root, it lists all home directories; otherwise, it lists the current user’s home directory.
  • It sets the directory list accordingly (/home/* for all users or $HOME for the current user).
  • For each directory, it counts files and subdirectories using find and calculates size with du.
  • The output is formatted in a table-like structure for clarity.

Below is output from my terminal:

<H2>Home Space Utilization for steve</H2>
<H3>/home/steve</H3>
<PRE>
    Dirs     Files      Size
    ----     -----      ----
      17        34      5.5M
</PRE>

Your Turn!

Now that you’ve learned about for loops, try creating a simple script that:

  1. Creates a directory called “practice”
  2. Creates 5 empty files named “file1.txt” through “file5.txt” in that directory
  3. Adds the text “This is file number X” to each file (where X is the file number)
See Solution
#!/bin/bash
mkdir -p practice
cd practice
for i in {1..5}; do
    echo "This is file number $i" > "file$i.txt"
    echo "Created file$i.txt"
done

Output from my terminal:

Created file1.txt
Created file2.txt
Created file3.txt
Created file4.txt
Created file5.txt

steve@server:~/sandbox$ ls -l
total 44
-rw-rw-r-- 1 steve steve  22 Apr 24 07:56 file1.txt
-rw-rw-r-- 1 steve steve  22 Apr 24 07:56 file2.txt
-rw-rw-r-- 1 steve steve  22 Apr 24 07:56 file3.txt
-rw-rw-r-- 1 steve steve  22 Apr 24 07:56 file4.txt
-rw-rw-r-- 1 steve steve  22 Apr 24 07:56 file5.txt

Key Takeaways

  • Two main loop types: Traditional shell form for lists and C-style for numeric counters
  • Multiple ways to create lists: Direct lists, brace expansion, pathname expansion, and command substitution
  • Common use cases: File processing, sequence generation, and command output iteration
  • Best practices: Quote variables, use meaningful names, and include error checking
  • Automation benefits: Save time and reduce errors in repetitive tasks

Conclusion

For loops are powerful tools that can significantly enhance your Linux scripting capabilities. By mastering both the traditional shell form and C language form, you can automate repetitive tasks, process files efficiently, and create more robust scripts. Start with simple examples and gradually build up to more complex applications as you gain confidence.

Don’t be afraid to experiment with different loop structures and techniques. The more you practice, the more natural loop creation will become.

Have questions or want to share your experience with for loops? Please leave a comment below! As mentioned in my author’s note, I’m learning too, and I’d love to hear your feedback and insights.


References

  1. Advanced Bash-Scripting Guide
  2. Bash Reference Manual - Looping Constructs
  3. Introduction to Linux Bash programming: 5 for loop tips
  4. Understanding Bash Loops: A Comprehensive Guide

Happy Coding! 🚀

For Loops in Linux

You can connect with me at any one of the below:

Telegram Channel here: https://t.me/steveondata

LinkedIn Network here: https://www.linkedin.com/in/spsanderson/

Mastadon Social here: https://mstdn.social/@stevensanderson

RStats Network here: https://rstats.me/@spsanderson

GitHub Network here: https://github.com/spsanderson

Bluesky Network here: https://bsky.app/profile/spsanderson.com

My Book: Extending Excel with Python and R here: https://packt.link/oTyZJ

You.com Referral Link: https://you.com/join/EHSLDTL6