FUN WITH LINUX

Bash: Loop Sequences

19 November 2014

Here are a some examples how to loop over a range of numbers using a “for-loop”:

Example1:

for i in 1 2 3 4 5 6 7 8 9 10 11 12; do echo $i; done

Output:

1
2
3
4
5
6
7
8
9
10
11
12

Example2:

for i in {1..10}; do echo 192.168.1.$i; done 

Output:

192.168.1.1
192.168.1.2
192.168.1.3
192.168.1.4
192.168.1.5
192.168.1.6
192.168.1.7
192.168.1.8
192.168.1.9
192.168.1.10

Example3(here we make a step-size of 2):

for i in {1..10..2}; do echo 192.168.1.$i; done 

Output:

192.168.1.1
192.168.1.3
192.168.1.5
192.168.1.7
192.168.1.9

Example4:

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

Output:

1
2
3
4
5
6
7
8
9
10

Example5:

for ((i = 0; i < 11; i++)); do echo $i; done

Output:

1
2
3
4
5
6
7
8
9
10
[ Linux  Programming  Bash  One-Liner  ]
Except where otherwise noted, content on this site is licensed under a Creative Commons Attribution 3.0 Unported License.

Copyright 2015-present Hoti