Introduction to Linux - A Hands on Guide | Linux Bible | Linux From Scratch | A Newbie's Getting Started Guide to Linux | Linux Command Line Cheat Sheet | More Linux eBooks



Friday, 23 December 2016

Bash Scripting - 'while' Loop

Bash 'while' loop - We have been discussing loops in bash scripting and we have covered one of its kinds, for loop, in our last article - Bash Scripting : 'for' Loops. In that article, we saw that, a loop is required in order to repeat a certain task a number of times. In for loop syntax, we created a loop using Initialization, Condition and Increment / Decrement. This article is about another kind of loop statement - while loop, in which we study its syntax and understand it in more details with examples.


Here we go!

The 'While' Loop

In while loop, we have a condition, which is checked after every iteration. As long as the condition stays True, the block of code keeps executing, thus forming a loop. As soon as the condition becomes False, the loop is terminated. Have a look on while loop syntax:

Syntax:

while [ Condition ]
do

    -- Block of Commands --

done

Example:

#!/bin/bash

n=1

while [ $n -le 5 ]
do
  echo "This is Iteration No. $n"
  n=$( expr $n + 1 )
done

In above code, we have n=1 before we enter the loop. When we enter the loop, the condition is checked whether n <= 5, which is True, and we enter the loop. Now, echo statement displays current value of n which is 1. Then, n is incremented by 1 (Please check our article on Arithmetic Operations for more details about expr). When the block ends, we have n=2 and the control goes back to while, where the condition is checked again. Condition follows, echo prints the value of n and increments its value by 1. So, after 5 iterations, we would have echo statement executed 5 times and with n incremented to value 6. At this point, control goes to while, condition is checked and does not follow. Hence the loop exits here. In the end, we have below result in the output.

Result:

This is Iteration No. 1
This is Iteration No. 2
This is Iteration No. 3
This is Iteration No. 4
This is Iteration No. 5

An Infinite 'while' Loop

An infinite while loop is the one, which never ends. For this, we need a condition which is always True. So, for this, you can mention any non-zero number or a non-empty string or a : (or a condition which is always True) as the condition, which is evaluated to True by bash. The condition always being True, the block of code will keep executing infinitely.

Example:

#!/bin/bash

while [ 1 ]
do
   echo "You are in an Infinite Loop. Press CTRL + C to Exit.."
done

OR

#!/bin/bash

while :
do
   echo "You are in an Infinite Loop. Press CTRL + C to Exit.."
done

OR


#!/bin/bash

while [ 5 -eq 5 ]
do
   echo "You are in an Infinite Loop. Press CTRL + C to Exit.."
done

'break' Statement

The break statements are used in the loops to exit from the loop prematurely, based on certain condition (Please take look over our article on Bash Conditionals). If the condition follows, break statement is executed, which then prevents further iterations from happening and exits from loop.

Syntax:

while [ condition ]
do
    -- Some Commands --

    if [ condition ]
    then
        break
    fi

    -- More commands --
done

Example:

#!/bin/bash

while :
do
    echo "Enter a single-digit number :"
    read n

    if [ "$n" -gt 9 ]
    then
        echo "Wrong Entry! Program will terminate now.."
        break
    fi
    
    echo "Good!"
done

'continue' Statement

The continue statement in a loop, when certain condition becomes true, skips all the subsequent statements, coming after it, and continues with the next iteration of the loop. So, when a continue statement is reached, further portion of code is skipped from execution and next iteration is started.

Syntax:

while [ condition ]
do
    -- Some Commands --

    if [ condition ]
    then
        continue
    fi

    -- More commands --
done

Example:

We take an example of printing all even numbers less than 20. In this case, we check whether a number is perfectly divisible by 2, using mod operator. If it is not, its clearly an odd number, so we prefer not to print it and skip further processing. For this, we introduce a continue statement in this condition, to prevent odd numbers from printing.

#!/bin/bash

i=0
while [ $i -le 20 ]
do
    i=$(expr $i + 1)
    j=$(expr $i % 2)

    if [ $j -ne 0 ]
    then
        continue
    fi

    echo "$i"
done

Result:


2
4
6
8
10
12
14
16
18
20

Example : Factorial of a Number

Factorial of a number is nothing but product of all natural numbers less or equal to the particular number. With this logic, we initialize a variable fact with 1. We then keep this value multiplying in each iteration, with the number getting decremented by 1, after every iteration. In the end, we get n * (n-1) * (n-2) * ... * 1 saved in the variable fact, which is the expected result.

#!bin/bash

echo "Enter the Number"
read num
n=$num
fact=1

while [ $num -ge 1 ]
do
    fact=$(expr $fact \* $num)
    num=$(expr $num - 1)
done

echo "Factorial( $n ) = $fact"

Result:

Enter the Number
6
Factorial( 6 ) = 720

With this, we have come to an end of this discussion on bash while loops. In this article, we've learned how while are constructed and how the control flow works. We have also revised how break and continue statements work in while loops. In the next article, we will learn about another loop statement - select loop. Please share your views and feedback in the comments section below and stay tuned. Thank you.

0 comments:

Post a Comment