Skip to content

Iteration over Sequences

Option 1 - Most flexible

Using ((expr1;expr2;expr3)) format. 

END=10
for ((i=1;i<=END;i=i+1)); do echo $i ; done 

Option 2 - Simple sequences

Numerical sequences

Using {a..b..c} format

for i in {1..10}; do echo $i; done      ## Output: 1 2 3 4 5 6 7 8 9 10
for i in {01..10}; do echo $i; done     ## Output: 01 02 03 04 05 06 07 08 09 10
for i in {001..010}; do echo $i; done   ## Output: 001 002 ... 009 010

# With specified increment of 2
for i in {1..10..2}; do echo $i; done   ## Output: 1 3 5 7 9

Using seq command

Using seq external command, calling it in one of 3 ways:

seq LAST - Sequence from 1 to LAST in increments of 1

seq FIRST LAST - Sequence from FIRST to LAST in increments of 1

seq FIRST STEP LAST - Sequence from FIRST to LAST with steps of STEP

Examples:

for i in $(seq 10); do echo $i; done
for i in $(seq 5 10); do echo $i; done
for i in $(seq 2 2 10); do echo $i; done 

For more info, see https://www.thegeekdiary.com/linux-seq-command-examples/ 

seq can use a format string: 

for name in $(seq -f "file_%g.txt" 1 2 10) ; do echo $name; done 

%g will be substituted with the numerical sequence specified (i.e. 1 through 10 in steps of 2) 

Alphabetical sequences

for i in {a..f}; do echo $i; done
for i in {A..F}; do echo $i; done 

Option 3 - Custom sequences

for i in {apple,bear,cat}; do echo $i; done