For Loops
Iterate over lists or ranges
Basic for loop
Simple for loop with list
#!/bin/bash
for i in 1 2 3 4 5; do
echo "Number: $i"
done
For loop with range
For loop with numeric range
#!/bin/bash
for i in {1..10}; do
echo "Number: $i"
done
For loop with step
For loop with step size
#!/bin/bash
for i in {1..10..2}; do
echo "Odd number: $i"
done
For loop over files
Iterate over files matching pattern
#!/bin/bash
for file in *.txt; do
echo "Processing file: $file"
done
For loop with array
Iterate over array elements
#!/bin/bash
fruits=("apple" "banana" "cherry")
for fruit in "${fruits[@]}"; do
echo "Fruit: $fruit"
done
For loop with C-style syntax
For loop using C-style syntax with arithmetic evaluation
#!/bin/bash
for (( i=1; i<=10; i++ )); do
echo "Number: $i"
done
For loop with step size
For loop with custom step size
#!/bin/bash
for (( i=0; i<=20; i+=2 )); do
echo "Even number: $i"
done
For loop with multiple variables
For loop with multiple variables
#!/bin/bash
for (( i=1, j=10; i<=5; i++, j-- )); do
echo "i=$i, j=$j"
done
For loop with command output
For loop iterating over command output
#!/bin/bash
for file in $(ls *.txt); do
echo "Processing: $file"
wc -l "$file"
done
For loop with glob patterns
For loop with multiple file extensions using glob patterns
#!/bin/bash
for file in /path/to/files/*.{txt,log,csv}; do
if [ -f "$file" ]; then
echo "Found file: $file"
fi
done
For loop with positional parameters
For loop processing all command line arguments
#!/bin/bash
for arg in "$@"; do
echo "Argument: $arg"
done
Bash for with process substitution
Bash for loop with process substitution
#!/bin/bash
for file in <(ls *.txt); do
echo "Processing: $file"
done
Bash for with IFS manipulation
Bash for loop with IFS (Internal Field Separator) manipulation
#!/bin/bash
IFS=$'\n'
for line in $(cat file.txt); do
echo "Line: $line"
done
unset IFS