Receive all updates via Facebook. Just Click the Like Button Below

For loop in shell scripts

A for loop is used to repeat the same set of code.
If we want our script to repeat the same set of code say around 10 or 100 times, we can use a for loop.

1

For Loops in Linux Shell Scripting

2

Syntax1:

 
for { variable name } in { list }
do
{ code to execute }
done
          

Syntax2:

 
for($start_num; Range; $increment)
do 
{ code to execute }
done
          

Example1: for1.sh

 
for ((  i = 0 ;  i <= 5;  i++  ))
do
  echo "Welcome $i times"
done
          

Result:

 
./for1.sh
Welcome 0 times
Welcome 1 times
Welcome 2 times
Welcome 3 times
Welcome 4 times
Welcome 5 times
          

In the above example the initial value of " i = 0 ".
The loop executed until the value of " i " reached 5.

Example2: for2.sh

 
# Get the value from the user
echo " Enter a value for the variable x:"
read x

# For loop
for (( a = $x; a <= 10; a++ ))
do
echo "The value of x is $a now"
done
          

Result:

 
./for2.sh
 Enter a value for the variable x:
7
The value of x is 7 now
The value of x is 8 now
The value of x is 9 now
The value of x is 10 now
          

Nested for loop
You can nest the for loop.
To understand the nesting of for loop try the following shell script.

Example: nested-for.sh

 
for (( i = 1; i <= 5; i++ ))      # 1st loop
do

    for (( j = 1 ; j <= 5; j++ )) # 2nd loop
    do
          echo  "The value of i is $i "
          echo  "The value of j is $j "
    done

  echo -e "\n"  ## print the new line

done
          

Result:

 
./nested-for.sh
The value of i is 1
The value of j is 1
The value of i is 1
The value of j is 2
The value of i is 1
The value of j is 3
......
.....
          

3

Related posts:

Advertise here

picture picture

Follow us

picture

- Tech-Tutorials twitter.com/techcuriosity

Like us

About Techcuriosity

I am Telson, the webmaster of Techcuriosity.com and through this site, I share my knowledge and curiosities in the Tech World.


What We Offer

  • What is ..?
  • How to ..?
  • Difference between ..?
  • How .. works?
  • Get in Touch

    techcuriosity@gmail.com
    UK : +44 77 33 890 678

    picture picture

    Our Partners

  • Website Design Dubai
  • SEO Link Exchange
  • picture

    picture