Thursday, April 7, 2022

Linux Shell Script for Loops

 Loops are repeated set of actions for a range of values.

For loop

Below are some Examples

echo "Fix values in for loop"
for i in 1 2 3 4 5
do
        echo $i
done

echo "Range values"
for i in {1..10}
do
        echo $i
done

echo "Step values with Range"
for i in {0..10..2}
do
        echo $i
done

echo "c style for loop"
for (( c=1; c<=5; c++ ))
do
        echo $c
done

echo "break statement example which exit from the loop whenever break statement is encountered"
for i in {1..10}
do
    if [ $i -eq 5 ]
    then
      break
    fi

        echo $i
done

echo "continue statement to continue the loop"
for i in {1..10}
do
    var1=`expr $i % 2`
    if [ $var1 -eq 0 ]
    then
      continue
    fi

        echo $i
done

echo "Looping with array"
Zones=('zone1' 'zone2' 'zone3')
for i in "${Zones[@]}"
do
        echo $i
done

Execute

./loop.sh

Output

Fix values in for loop

1

2

3

4

5

Range values

1

2

3

4

5

6

7

8

9

10

Step values with Range

0

2

4

6

8

10

c style for loop

1

2

3

4

5

break statement example which exit from the loop whenever break statement is encountered

1

2

3

4

continue statement to continue the loop

1

3

5

7

9

Looping with array

zone1

zone2

zone3

While loop

It repeats the set of statements on the basis of conditions which are supplied with the while loop

choice="Y"
while [ $choice == "Y" ]
do
        echo "Enter the choice(Y/N)"
        read choice
done
echo "Program ends here"

Execute

./loop.sh







2 comments:

Sunil Donthula said...

BREAK and CONINUE are acting like commands in IF statement what are they?

Sunil Donthula said...

are they shell scripting commands?

Post a Comment