Bash for Loop in Linux
Definitions
Loops are a set of commands that the computer repeats until a certain condition is met. They can be broken before that condition is met with a specific command. They are used for counting, searching for information, or populating data structures.
In computer science there are two main loops: the for loop and the while loop.
for loop:
In computer science, a for loop is a programming language statement which allows code to be repeatedly executed. It is classified as an iteration statement. Unlike many other kinds of loops, such as the while loop, the for loop is often distinguished by an explicit loop counter or loop variable.
while loop:
In most computer programming languages, a while loop is a control flow statement that allows code to be executed repeatedly based on a given boolean condition. The while loop can be thought of as a repeating if statement.
With that understood, let's start with the Bash for loop article.
How to use bash for loop
In Bash there are two ways to implement a for loop:
- Instruct
forto act on a predefined list of elements, using thefor … instatement. - Use C syntax:
for (( exp1, exp2, exp3 )).
Simple examples of each:
Using for ... in statement
for i in 1 2 3 4
do
echo "Number $i"
done
Using for ((exp1, exp2, exp3)) statement
for (( i=1; i<=4; i++))
do
echo "Number $i"
done
The result is the same in both cases:
Number 1
Number 2
Number 3
Number 4
Examples
Counting:
#!/bin/bash
for i in {1..25}
do
echo $i
done
Or:
#!/bin/bash
for ((i=1;i<=25;i+=1))
do
echo $i
done
Counting in n steps:
#!/bin/bash
for i in {0..25..5}
do
echo $i
done
This counts in steps of 5.
Counting backwards:
#!/bin/bash
for i in {25..0..-5}
do
echo $i
done
Acting on files:
One of the best uses for a for loop in Bash is working with files:
for file in ~/*.md
do
echo $file
done
That example lists all files with .md extension — equivalent to ls *.md.
Break and continue in the for loop
Sometimes you want to stop the loop before it finishes. For example, when you are waiting for a condition to be met:
for i in [series]
do
command1
command2
if (condition)
then
break
fi
command3
done
With break you stop the loop completely. With continue, you skip to the next value in the series without running the remaining commands in that iteration:
for i in [series]
do
command1
command2
if (condition)
continue
fi
command3
done
One-liner bash for loop
When working in the command line, you often write for loops as one-liners rather than inside a script.
Using one-liners with counters:
for i in {1..3}; do echo 'hello'; done
Or:
for ((i=1;i<=3;i++)); do echo "hello"; done
Even numbers up to 30:
for ((i=0;i<=30;i+=2)); do echo "$i is even"; done
Copy all PDF files to a backup directory:
for i in *.pdf; do cp $i /backup/; done
Add a .bak extension to all .txt files:
for i in *.txt; do mv $i $(basename $i .txt).bak; done
Last edit on: June 2nd, 2019
Last updated on: June 26, 2026
By: Guillermo Garron