The Bash for loop is a control structure that allows you to execute a sequence of commands repeatedly. It is commonly used in automating repetitive tasks, such as processing files, iterating over arrays, and executing commands across multiple servers.

This guide provides practical and advanced examples, including infinite loops, conditional exits, iterating over arrays, command substitution, handling command-line arguments, and more.


Syntax of the Bash For Loop

The basic syntax of a for loop in Bash is:

for VARIABLE in list_of_values
do
   command1
   command2
   commandN
done

Example: Iterating Over a List of Numbers

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

Example: Iterating Over Files

for file in file1.txt file2.txt file3.txt
do
   echo "Processing $file"
done

Example: Iterating Over Command Output

for user in $(cat users.txt)
do
   echo "Creating account for $user"
done

Example 1: Printing a Message Multiple Times

The following script prints "Welcome X times" five times:

#!/bin/bash
for i in 1 2 3 4 5
do
   echo "Welcome $i times"
done

Another way to define a range of numbers is using {start..end}:

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

To define an increment step, use {start..end..step}:

for i in {0..10..2}
do
   echo "Value: $i"
done

Expected Output:

Value: 0
Value: 2
Value: 4
Value: 6
Value: 8
Value: 10

Example 2: Using the seq Command in a For Loop

For older Bash versions (pre-3.0), use seq:

for i in $(seq 1 2 10)
do
   echo "Odd number: $i"
done

⚠️ Note: Modern Bash versions should use {start..end..step} instead of seq for better efficiency.


Example 3: C-Style For Loop in Bash

A C-style for loop in Bash follows this syntax:

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

Example:

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

Expected Output:

Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5

Example 4: Infinite For Loop

A for loop can run indefinitely with empty expressions:

#!/bin/bash
for (( ; ; ))
do
   echo "Infinite loop... (Press CTRL+C to stop)"
done

Example 5: Exiting a For Loop with break

The break command terminates the loop when a specific condition is met:

for i in {1..10}
do
   if [ $i -eq 5 ]; then
      echo "Exiting loop at iteration $i"
      break
   fi
   echo "Iteration $i"
done

Expected Output:

Iteration 1
Iteration 2
Iteration 3
Iteration 4
Exiting loop at iteration 5

Example 6: Skipping Iterations with continue

The continue command skips the current iteration and proceeds to the next:

for i in {1..10}
do
   if [ $(( i % 2 )) -eq 0 ]; then
      continue
   fi
   echo "Odd number: $i"
done

Expected Output:

Odd number: 1
Odd number: 3
Odd number: 5
Odd number: 7
Odd number: 9

Example 7: Iterating Over an Array

Using a for loop to iterate over an array of server names:

SERVERS=("server1" "server2" "server3")

for server in "${SERVERS[@]}"
do
   echo "Connecting to $server..."
   ssh root@$server "uptime"
done

Example 8: Iterating Over a Variable

Storing file names in a variable and looping through them:

FILES="file1.txt file2.txt file3.txt"

for f in $FILES
do
   echo "Processing $f"
done

Example 9: Iterating Over Files in a Directory

This script lists and processes all files in a directory:

for file in /path/to/directory/*
do
   echo "Processing $file"
done

Example 10: Command Substitution in a For Loop

Using the output of a command in a loop:

for user in $(cut -d: -f1 /etc/passwd)
do
   echo "User: $user"
done

Example 11: Iterating Over Command-Line Arguments

Processing arguments passed to the script:

#!/bin/bash
for arg in "$@"
do
   echo "Argument: $arg"
done

Usage Example:

$ ./script.sh one two three

Expected Output:

Argument: one
Argument: two
Argument: three

Example 12: Pinging Multiple IPs

This script pings multiple IPs and displays response times:

#!/bin/bash
IPS="8.8.8.8 8.8.4.4 9.9.9.9 1.1.1.1"

for ip in $IPS
do
   ping -c 4 "$ip"
done

Summary

  • The for loop automates repetitive tasks by iterating over lists, files, or command outputs.
  • You can define number ranges using {start..end..step}.
  • Infinite loops can be created using for ((;;)).
  • The loop can exit early using break or skip iterations using continue.
  • Useful for processing files, executing commands remotely, and iterating over command-line arguments.

Further Reading

For more Bash scripting insights, explore the following resources:

You can also access Bash documentation from your terminal:

man bash
help for
help continue
help break

Have questions or need more examples? Try these scripts and let me know how they work for you! 🚀

Scroll to Top