Bash For Loop
Bash For loop is a statement that lets you repeat a set of Bash commands over a list of values. The list may contain words, filenames, numbers, array elements, command output, or generated sequences.
Use a Bash for loop when the number of items is already known or can be generated before the loop starts. For example, it is useful for processing files in a directory, printing array values, running the same command for several users, or repeating commands for a range of numbers.
Bash For Loop Syntax for Lists, Arrays, and Counters
The most common Bash for loop syntax is:
for variable in item1 item2 item3
do
command1
command2
done
You can also write the same loop on one line by using semicolons. This form is often used directly in the terminal.
for variable in item1 item2 item3; do command; done
The variable receives one item at a time. The commands between do and done run once for each item.
In this tutorial, we will go through following topics.
- Example – Iterate over elements of an Array
- Example – Consider white spaces in String as word separators
- Example – Consider each line in string as a separate word
- Example – Iterate over a Sequence
- Example – Using a counter
- Example – With break command
- Example – Skip one iteration with continue
- Example – Loop over files that match a pattern
Bash For Loop – Iterate over Elements of Array
The syntax to loop or iterate over elements of an array using Bash For loop is
#!/bin/bash
arr=( "element1" "element2" . . "elementN" )
for i in "${arr[@]}"
do
echo $i
#statement(s)
done
For each element in arr the statements from do till done are executed, and each element could be accessed as i within the for loop for respective iteration.
Keep the array expansion inside double quotes as "${arr[@]}". This preserves array elements that contain spaces, such as "shell script", as one value.
Bash For Loop Example
In this For loop example, we will take an array of three strings, and iterate over the elements of array.
Bash Script File
#!/bin/bash
# declare an array
arr=( "bash" "shell" "script" )
# for loop that iterates over each element in arr
for i in "${arr[@]}"
do
echo $i
done
When the above bash for loop example is run in Terminal, you will get the following output.
Output
~$ ./bash-for-loop-example-4
bash
shell
script
Bash For Loop – Whitespaces in String as Word Separators
The syntax of Bash For loop to consider whitespaces in given string as word separators is
#!/bin/bash
for word in $str;
do
#statement(s)
done
str is a string
for each word in str the statements from do till done are executed, and word could be accessed within the for loop for respective iteration.
This form intentionally leaves $str unquoted, so Bash performs word splitting. It is useful only when you really want spaces, tabs, and newlines to split the string into separate words. If the string contains filenames or values with spaces, use an array instead.
Example
In the following example, we will take a string with words separated by white spaces, and iterate over the words using for loop.
Bash Script File
#!/bin/bash
str="this example
demonstrates the for loop
that considers all white-space
characters as word separators"
## now loop through the above array
for i in $str;
do
echo "$i"
done
When the above bash for loop example is run in Terminal, you will get the following output.
Output
~$ ./bash-for-loop-example
this
example
demonstrates
the
for
loop
that
considers
all
white-space
characters
as
word
separators
Bash For Loop – Each Line in String as Element
The syntax of Bash For Loop to consider each line in string as element is
#!/bin/bash
for line in "$str";
do
#statement(s)
done
str is a string
for each line that is a line in str, statements from do till done are executed, and line could be accessed within the for loop for respective iteration.
Note: Observe that the only difference between first type of for loop and this one is the double quotes around string variable.
When "$str" is quoted, Bash treats the whole string as one item. The embedded newline characters are preserved when the variable is printed, so the output appears on multiple lines. If you need a separate loop iteration for every line, use the line-reading example shown after the existing example.
Example
In the following example, we will take a string with four lines. We will use for loop to iterate over the elements in string separated by new line.
Bash Script File
#!/bin/bash
str="this example
demonstrates the for loop
that considers new line
characters as line separators"
## loop through each line in above string
for line in "$str"
do
echo "$line"
done
When the above bash for loop example is run in Terminal, we will get the following output.
Output
~$ ./bash-for-loop-example-2
this example
demonstrates the for loop
that considers new line
characters as word separators
Bash Script to Process Each Line as a Separate Iteration
For line-by-line processing, a while read loop is more reliable than a for loop because it preserves spaces in each line.
#!/bin/bash
str="first line
second line
third line"
while IFS= read -r line
do
echo "Line: $line"
done <<< "$str"
Bash For Loop – Iterate Over a Sequence
The syntax of Bash For loop to iterate over a sequence of numbers is
#!/bin/bash
for i in `seq m n`;
do
#statement(s)
done
for loop is iterated for each element i in the sequence from m to n . The element in the sequence, <span style="font-family: Courier 10 Pitch, Courier, monospace;"><span style="font-size: 12.8px; background-color: #d2eeca;">i</span></span> is accessible during the iteration.
In Bash, brace expansion is another common way to loop over a fixed range of numbers.
for i in {1..5}
do
echo "$i"
done
Brace expansion is expanded before the loop runs. Use seq when the range values are calculated at runtime or stored in variables.
Example
In the following Bash Script, we will use For Loop to iterate over a sequence of numbers.
Bash Script File
#!/bin/bash
for i in `seq 1 10`;
do
echo $i
done
When the above bash for loop example is run in Terminal, you will get the following in the output.
Output
~$ ./bash-for-loop-example-3
1
2
3
4
5
6
7
8
9
10
Bash For Loop – Use Counter to Iterate Over Elements of Array
The syntax of Bash For Loop to use a variable for counter to iterate over elements of an array is
#!/bin/bash
array=( "element1" "element2" . . "elementN" )
arraylength=${#array[@]}
for (( i=1; i<${arraylength}+1; i++ ));
do
echo $i : " ${array[$i-1]}
#statement(s)
done
Length of an array could be calculated using ${#array[@]} and the the statements from do till done are could iterated based on a condition. The syntax of for loop might look similar to that of Java For Loop.
A counter loop is useful when you need both the index and the value. Bash array indexes start at 0, but the example below prints a human-friendly count starting from 1.
Example
In the following Bash Script, we will use For Loop to iterate over an Array using a counter variable.
Bash Script File
#!/bin/bash
#array variable
arr=( "bash" "shell" "script" )
# get length of an array to a variable
arrlength=${#arr[@]}
# for loop to read all values and indexes
for (( i=1; i<${arrlength}+1; i++ ));
do
echo $i " : " ${arr[$i-1]}
done
When the above bash for loop example is run in Terminal, we will get the following output.
Output
~$ ./bash-for-loop-example-5
1 : bash
2 : shell
3 : script
Bash For Loop – Break Command
The syntax of For Loop with break command, to break the for loop abruptly even before the for condition fails is
#!/bin/bash
array=( "element1" "element2" . . "elementN" )
for i in "${array[@]}"
do
#statement(s)
if [ BREAKING_CONDITION ]; then
break
fi
done
BREAKING_CONDITION decides when to break the for loop prematurely. When the breaking condition evaluates to TRUE, then break statement is executed. break command breaks the loop that is immediate to the break statement.
Example
In the following Bash Script, we will write a For Loop containing break statement. The break statement is surrounded in an if statement, which executes the body when the element is “script”. In other words, we are breaking the for loop if the element is “script”.
Bash Script File
#!/bin/bash
# declare an array
arr=( "bash" "shell" "script" "language" )
# for loop that iterates over each element in arr
for i in "${arr[@]}"
do
echo $i
# break for loop based on a condition
if [ $i == "script" ]; then
break
fi
done
When the above bash for loop example is run in Terminal, we will get the following output.
Output
~$ ./bash-for-loop-example-6
bash
shell
script
Bash For Loop – Continue Command to Skip an Item
The continue command skips the remaining commands in the current iteration and moves the loop to the next item. It is useful when one value should be ignored, but the loop should not stop completely.
#!/bin/bash
arr=( "bash" "skip" "shell" "script" )
for item in "${arr[@]}"
do
if [ "$item" = "skip" ]; then
continue
fi
echo "$item"
done
In this example, the value skip is not printed, but the loop continues with the remaining array elements.
bash
shell
script
Bash For Loop – Loop Over Files Matching a Pattern
A Bash for loop is often used with filename patterns. The following script prints the names of all .txt files in the current directory.
#!/bin/bash
for file in *.txt
do
echo "Text file: $file"
done
When looping over files, quote the variable as "$file" inside commands. This prevents filenames with spaces from being split into multiple arguments.
#!/bin/bash
for file in *.txt
do
cp "$file" "backup/$file"
done
Bash For Loop Forms and When to Use Them
| Bash for loop form | Best used for | Example pattern |
|---|---|---|
for item in list | Words, array values, filenames, command output | for name in Alice Bob |
for item in "${array[@]}" | Array elements, including values with spaces | for item in "${arr[@]}" |
for i in {1..10} | Fixed numeric ranges | for i in {1..10} |
for i in `seq 1 10` | Numeric ranges generated by a command | for i in `seq $start $end` |
for (( ... )) | Counter-based loops with arithmetic conditions | for (( i=0; i<5; i++ )) |
Common Bash For Loop Mistakes
- Forgetting
doordone: Every multi-line Bash for loop needs both keywords. - Using unquoted variables inside commands: Use
"$file"or"$item"when the value may contain spaces. - Expecting quoted strings to split into words:
"$str"is one item;$stris split by whitespace. - Using a for loop for line-by-line file reading: Prefer
while IFS= read -r linefor reading files or multiline text safely. - Assuming file patterns always match: If no file matches
*.txt, Bash may keep the literal pattern depending on shell options.
FAQs on Bash For Loop Syntax and Examples
What is the syntax of a Bash for loop?
The common syntax is for variable in list; do commands; done. In a multi-line script, place do and done on separate lines for readability.
How do I loop through an array in Bash?
Use for item in "${array[@]}". The quotes preserve each array element exactly, including values that contain spaces.
How do I write a Bash for loop from 1 to 10?
Use for i in {1..10}; do echo "$i"; done for a fixed range, or use seq when the start and end values are stored in variables.
What is the difference between break and continue in a Bash for loop?
break stops the loop completely. continue skips only the current iteration and then proceeds with the next item.
Should I use a Bash for loop to read every line of a file?
For line-by-line file reading, use while IFS= read -r line. A for loop splits text on whitespace by default, which can change lines that contain spaces.
Editorial QA Checklist for Bash For Loop Tutorials
- Check that each Bash for loop has matching
for,do, anddonekeywords. - Confirm that array examples use
"${array[@]}"when preserving elements is important. - Verify that output blocks match the shown Bash script examples.
- Make sure line-by-line processing is not confused with whitespace-based word splitting.
- Review whether each new code block uses the correct PrismJS class, such as
language-bash,language-bash syntax, oroutput.
Conclusion
In this Bash Tutorial – Bash For Loop, we have learnt to iterate specific set of statements over words, lines in a string, elements in a sequence or elements in an array with the help of Bash Script examples. We also covered counter loops, break, continue, file patterns, and common quoting mistakes that affect Bash loop behavior.
TutorialKart.com