Bash for loop and seq

In Linux if we want to repeat an execution there is a simple way to do this.

First we have the seq command that with the following structure:


seq <number>

and it will output all numbers from 1 to the <number> ( with difference of 1 between number to the next one), every  number with its own line.

for example seq 10 will give us all number from 1 to 10


$ seq 5
1
2
3
4
5

if we give seq two arguments, then the first one will be the first number (default 1)  and the second will be the last number.
for example to count from 5 to 10:


bob@vmUbuntu:~$ seq 5 10
5
6
7
8
9
10

if we give seq 3 arguments, then the first is the first number (from it the counting start), second the size of the step (between 1 number and the next one) and the third is the last number that close the number list.
For example to count from 2 to 8 with step of size 2:


bob@vmUbuntu:~$ seq 2 2 8
2
4
6
8

As itself it may not look  very useful but we can combine it with for loop to repeat actions number of times:
The structure of the for loop


for <variableName> in <list of values separate by spaces or new line>; do 
list of commands to execute, $variableName is accessible here  
done

In the below example we have for loop that run from 1 to 10 and display 10 lines, each line the word “number” follow by the number.


$ for num in $(seq 10); do
> echo "number $num"
> done
number 1
number 2
number 3
number 4
number 5
number 6
number 7
number 8
number 9
number 10

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s