Linux Bash For Loop Range Examples – POFTUT

Linux Bash For Loop Range Examples


Bash for loop is popular programming structure used by a lot of Linux system administrators. For loops can be used in a lot of different cases. We have all ready examined the bash while and for loop in the following tutorial.

Bash For and While Loop Examples

In this tutorial we will look more specific topic named for loop with range

Specify Range with Numbers

Linux bash provides mechanism to specify range with numbers. We will use {FIRST..LAST}. We need to specify the start and end numbers where the range will be incremented one by one by default. In this example we will use range from 1 to 10 .

$ for i in {1..10}; do echo $i; done
Specify Range with Numbers
Specify Range with Numbers

Specify Range with Numbers By Specifying Increment Value

In previous example we have incremented the range one by one by default. But in some situations we may need to increment numbers different than one. We will use {FIRST..LAST..INCREMENT}. We will start from 1 to the 10 and increment 2 in this example.

$ for i in {1..10..2}; do echo $i; done
Specify Range with Numbers Different Increment
Specify Range with Numbers Different Increment

Specify Range with Seq Command

seq is a command or tool used in bash which provides sequential data or numbers. Syntax is like below.

seq FIRST LAST

We will set first 1 and last as 10 in this example.

$ for i in $(seq 1 10); do echo $i; done
Specify Range with Seq Command
Specify Range with Seq Command

Specify Range with Seq Command By Specifying Increment Value

seq command can be also used to specify different increment value than 1 . The seq command with different increment value is like below.

seq FIRST INCREMENT LAST

In this example we will start from 1 and increment with 2 up to 10

$ for i in $(seq 1 2 10); do echo $i; done
Specify Range with Seq Command By Specifying Increment Value
Specify Range with Seq Command By Specifying Increment Value

LEARN MORE  Linux /bin/bash Shell and Script Tutorial

Leave a Comment