Bash For Loop Examples
The for loop is a fundamental control flow statement in Bash scripting, allowing you to iterate over a sequence of items. This page provides various examples of how to use the for loop for different purposes, from simple number sequences to processing command output and file patterns.
Basic Number Iteration
This is the most straightforward use of a for loop, iterating through a list of numbers.
# basic loop
for i in 1 2 3 4 5 6 7 8 9 10
do
echo $i
done
Iterating Over Command Output
You can use command substitution (backticks or $()) to loop over the output of a command, such as ls.
# loop ls command results
for var in `ls -alF`
do
echo $var
done
Looping Through File Patterns
A common use case is to iterate over files matching a specific pattern, like all JPG files in the current directory.
# loop over all the JPG files in the current directory
for jpg_file in *.jpg
do
echo $jpg_file
done
Generating Number Sequences with seq
The seq command is useful for generating sequences of numbers, which can then be used in a for loop.
# loop specified number of times
for i in `seq 1 10`
do
echo $i
done
# same as above, but as one-liner
for i in `seq 1 10`; do echo $i; done
C/C++ Style For Loop
Bash also supports a C-style for loop syntax for more traditional iteration.
# loop specified number of times: the C/C++ style
for ((i=1;i<=10;++i))
do
echo $i
done
Brace Expansion for Sequences
Brace expansion provides a concise way to generate sequences of numbers or characters.
# loop specified number of times: the brace expansion
for i in {1..10}
do
echo $i
done
Further Learning
To deepen your understanding of Bash scripting and loops, consider exploring resources like: