How to Iterate Lists in Bash Scripting

ShellShellBeginner
Practice Now

Introduction

In this tutorial, we will explore how to use a for loop in Bash to iterate from 1 to 10. Bash scripting is a powerful tool for automating tasks, and understanding for loops is a fundamental skill. By the end of this guide, you'll be able to confidently use for loops in your Bash scripts to perform a wide range of operations.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL shell(("`Shell`")) -.-> shell/BasicSyntaxandStructureGroup(["`Basic Syntax and Structure`"]) shell(("`Shell`")) -.-> shell/VariableHandlingGroup(["`Variable Handling`"]) shell(("`Shell`")) -.-> shell/ControlFlowGroup(["`Control Flow`"]) shell(("`Shell`")) -.-> shell/SystemInteractionandConfigurationGroup(["`System Interaction and Configuration`"]) shell/BasicSyntaxandStructureGroup -.-> shell/shebang("`Shebang`") shell/BasicSyntaxandStructureGroup -.-> shell/comments("`Comments`") shell/VariableHandlingGroup -.-> shell/variables_usage("`Variable Usage`") shell/ControlFlowGroup -.-> shell/for_loops("`For Loops`") shell/SystemInteractionandConfigurationGroup -.-> shell/exit_status_checks("`Exit Status Checks`") subgraph Lab Skills shell/shebang -.-> lab-392732{{"`How to Iterate Lists in Bash Scripting`"}} shell/comments -.-> lab-392732{{"`How to Iterate Lists in Bash Scripting`"}} shell/variables_usage -.-> lab-392732{{"`How to Iterate Lists in Bash Scripting`"}} shell/for_loops -.-> lab-392732{{"`How to Iterate Lists in Bash Scripting`"}} shell/exit_status_checks -.-> lab-392732{{"`How to Iterate Lists in Bash Scripting`"}} end

Introduction to Bash Loops

What Are Bash Loops?

Bash loops are fundamental constructs in shell programming that enable repetitive task execution in Linux systems. They allow developers to automate processes, iterate through data, and perform systematic operations efficiently. In bash scripting, loops provide a powerful mechanism for linux automation and streamlined shell programming.

Core Loop Concepts

Loops in bash typically serve two primary purposes:

  • Executing commands multiple times
  • Processing collections of data systematically
graph LR A[Input Data] --> B{Loop Condition} B --> |True| C[Execute Commands] C --> B B --> |False| D[Exit Loop]

Basic Loop Types in Bash

Loop Type Primary Use Execution Pattern
For Loop Iterate through lists Fixed number of iterations
While Loop Conditional execution Dynamic termination
Until Loop Inverse conditional execution Runs until condition is true

Simple Bash Loop Example

#!/bin/bash
## Demonstration of basic for loop in bash scripting

fruits=("apple" "banana" "cherry" "date")
for fruit in "${fruits[@]}"
do
    echo "Current fruit: $fruit"
done

This example demonstrates a fundamental for loop structure in bash, showcasing how shell programming can efficiently process array elements through iterative execution.

Mastering For Loop Syntax

Standard For Loop Structures

Bash provides multiple for loop syntax patterns to handle different iteration scenarios in shell scripting. Understanding these structures enables efficient bash iteration and flexible shell scripting techniques.

Classic List Iteration

#!/bin/bash
## List iteration demonstration

servers=("web01" "db02" "cache03")
for server in "${servers[@]}"
do
    echo "Checking status of $server"
done

Range-Based Iteration

#!/bin/bash
## Numeric range iteration

for i in {1..5}
do
    echo "Current iteration: $i"
done

C-Style For Loop

#!/bin/bash
## C-style loop structure

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

Loop Syntax Comparison

graph TD A[For Loop Types] --> B[List Iteration] A --> C[Range Iteration] A --> D[C-Style Iteration]

Key Loop Iteration Patterns

Iteration Type Syntax Use Case
List Iteration for item in list Process array elements
Range Iteration for i in {start..end} Generate sequential numbers
C-Style for ((init;condition;increment)) Complex numeric iterations

Real-World Loop Applications

Batch File Processing

#!/bin/bash
## Automated file processing script

for file in /path/to/documents/*.txt
do
    filename=$(basename "$file")
    echo "Processing file: $filename"
    grep -l "error" "$file" >> error_log.txt
done

System Resource Monitoring

#!/bin/bash
## Multiple server health check

servers=("web01" "db02" "cache03")
for server in "${servers[@]}"
do
    ssh $server "df -h; free -m; top -bn1 | head -5"
done

Automated Backup Script

#!/bin/bash
## Incremental backup loop

backup_dirs=("/home" "/etc" "/var/log")
for dir in "${backup_dirs[@]}"
do
    tar -czf "backup_$(date +%Y%m%d)_${dir//\//_}.tar.gz" "$dir"
done

Loop Application Workflow

graph TD A[Input Data] --> B{Loop Processing} B --> C[File Manipulation] B --> D[System Monitoring] B --> E[Automated Tasks]

Common Loop Application Patterns

Application Type Primary Function Typical Use Case
File Processing Batch Operations Log analysis, file sorting
System Monitoring Resource Tracking Server health checks
Automated Backup Data Protection Incremental system backups
Network Scanning Connectivity Tests Server availability checks

Summary

Mastering the for loop in Bash is a crucial skill for any Bash programmer. In this tutorial, you've learned how to use a for loop to iterate from 1 to 10, with practical examples and best practices. By understanding the syntax and use cases of Bash for loops, you can streamline your scripting workflows and automate repetitive tasks more efficiently. Remember to apply these techniques in your own Bash scripts to enhance your productivity and problem-solving abilities.

Other Shell Tutorials you may like