Bash Loop Basics
Understanding Bash Loops in Shell Scripting
Loops are fundamental constructs in bash shell scripting that enable repetitive task execution. They allow developers to automate processes by iterating through data sets, performing actions on multiple items efficiently.
Basic Loop Types in Bash
Bash provides several loop structures for different iteration scenarios:
Loop Type |
Primary Use |
Syntax Complexity |
For Loop |
Iterating over lists/arrays |
Low |
While Loop |
Conditional repetition |
Medium |
Until Loop |
Inverse conditional iteration |
Medium |
For Loop Examples
Basic List Iteration
#!/bin/bash
fruits=("apple" "banana" "cherry")
for fruit in "${fruits[@]}"; do
echo "Current fruit: $fruit"
done
This script demonstrates a simple bash for loop, iterating through an array of fruits and printing each item.
Range-Based Iteration
#!/bin/bash
for number in {1..5}; do
echo "Counting: $number"
done
Demonstrates bash shell scripting's compact range iteration technique.
C-Style For Loop
#!/bin/bash
for ((i=0; i<5; i++)); do
echo "Iteration $i"
done
Provides a traditional C-style loop structure in bash programming, offering more control over iteration parameters.
Loop Flow Control
Bash loops support break
and continue
statements for advanced iteration management:
flowchart TD
A[Start Loop] --> B{Condition}
B --> |True| C[Execute Loop Body]
C --> D{Control Statement}
D --> |continue| B
D --> |break| E[Exit Loop]
B --> |False| E
This mermaid flowchart illustrates loop flow control mechanisms in linux iteration scenarios.