Unix
In this tutorial we will learn about For loop in Shell Programming.
Loop is used to execute a block of code multiple times.
We use for loop to iterate through a list of items.
for variable in items
do
# code for each item
done
Where, variable
holds an item from the list of multiple items.
In the following example we will use for loop to print from 1 to 5.
#!/bin/sh
for i in 1 2 3 4 5
do
echo $i
done
Output:
$ sh example01.sh
1
2
3
4
5
We use the brace expansion {m..n}
to generate string in shell script.
Example:
{1..5} will give 1 2 3 4 5
{a..f} will give a b c d e f
{Z..T} will give Z Y X W V U T
{-5..5} will give -5 -4 -3 -2 -1 0 1 2 3 4 5
{A,B,C,D} will give A B C D
{A,B,C{1..3},D} will give A B C1 C2 C3 D
#!/bin/sh
for i in {1..10}
do
echo $i
done
Where, {1..10}
will expand to 1 2 3 4 5 6 7 8 9 10
.
#!/bin/sh
for ch in {A..Z}
do
echo $ch
done
For this example we will use the *
which is a special character and it helps to list all the files in the current directory.
#!/bin/sh
for f in *
do
echo $f
done
Output:
$ sh example04.sh
example01.sh
example02.sh
example03.sh
example04.sh
We use the seq
command to generate numeric sequence.
Example:
seq LAST
so, seq 5 will give
1
2
3
4
5
seq FIRST LAST
so, seq 7 10 will give
7
8
9
10
seq FIRST INCREMENT LAST
so, seq 1 2 10 will give
1
3
5
7
9
For this we can use the seq
command and set FIRST to 1, INCREMENT to 2 and LAST to 10.
#!/bin/sh
for i in $(seq 1 2 10)
do
echo $i
done
Output:
$ sh example05.sh
1
3
5
7
9
Following is the syntax to create for loop in shell script that looks simiarl to for loop in C programming.
for (( var=val; var<=val2; var++ ))
do
# body of for loop
done
#!/bin/sh
for(( i = 1; i <= 5; i++ ))
do
echo $i
done
Output:
$ sh example06.sh
1
2
3
4
5
We can nest one for loop inside another.
for var_outer in list_outer
do
# outer for loop body
for var_inner in list_inner
do
# inner for loop body
done
done
1
1 2
1 2 3
1 2 3 4
To achive this we will use nested for loops. The first loop will help to manage the rows and the second for loop will help in printing the numbers per row.
#!/bin/sh
for r in {1..4}
do
for i in $(seq 1 $r)
do
printf "$i "
done
printf "\n"
done
In the above code we are using printf which helps in printing the result in the terminal.
ADVERTISEMENT