Skip to content

Iterating Over Data in Bash Scripts

Discover diverse examples of for loops in Bash scripts, showcasing different techniques for iterating over data. From numeric ranges to arrays, file contents, command output, and glob patterns, these examples demonstrate the versatility of for loops in processing data efficiently.

Whether you're automating tasks or enhancing script functionality, these examples offer valuable insights for leveraging for loops effectively in your Bash scripts.

For sample
for i in $( whoami ); do
    echo item: $i
done
Numeric Range
for i in {1..10}; do
    # Loop body
    echo $i
done
C-Style Loop
for ((i=1; i<=10; i++)); do
    # Loop body
    echo $i
done
Iterating over an Array
my_array=("apple" "banana" "orange")

for fruit in "${my_array[@]}"; do
    echo $fruit
done
Reading Lines from a File
while IFS= read -r line; do
    echo $line
done < input.txt
Command Output
for file in $(ls); do
    echo $file
done
Glob Pattern Matching
for file in *.txt; do
    echo $file
done
Arithmetic Progression
for ((i=0; i<=10; i+=2)); do
    # Loop body
    echo $i
done