While Loop in Shell Script Examples

WHILE LOOP IN SHELL SCRIPT



While Loop
  • It is an example of looping statements or iteration statements
  • It is used to execute the statements, if the condition is true otherwise it will skip the loop
  • It is an alternative for normal for loop.

Syntax
    while [ condition ] 
    do
true statement
    done


Types of Styles

  1. Shell Style
  2. C Style

Shell Style 

  • Here, we have to use the default shell style of syntax for writing the expression in the shell script.
C Style in Shell Script

  • Here, we can write code for expression using c language style using double braces ((expression))

1. C STYLE BASED FACTORIAL CODE

Source Code

     echo "--------------------------"
    echo -e "\t Factorial Program"
    echo "--------------------------"
    echo "Enter a Number: "
    read n
# define the variable
    f=1
    i=1
# define the while loop
    while ((i<=n)) 
    do
        f=$((f*i))
        ((i++))
    done
    echo "Fact is: $f"

Output
















2. SHELL STYLE BASED FACTORIAL CODE

Source Code

echo "--------------------------"
echo -e "\t Factorial Program"
echo "--------------------------"
echo "Enter a Number: "
read n
# define the vairable
f=1
i=1
# define while loop
while [ $i -le $n ]
do
    f=`expr $f \* $i`
# increment the variable i
    i=`expr $i + 1`
done
echo "The Factorial is: $f"

Note
  • expr is a linux command which is used to perform basic arithmetic operations such as addition, subtraction, multiplication, division, modulus operation, etc,...
Output




















IMPORTANT NOTE
    • In shell script, the operators can't be used directly. Instead this can be used as keywords.

            Operator                Keywords
                <                 -lt
                    <=         -le
                    >                 -gt
                    >=         -ge
                    ==         -eq
                    !=                 -ne

Infinite While loop
  • It is an important to note that, the colon (:) operator or true keyword is used for creating an infinite loop
  • The colon (:) operator is used instead of the operator symbols [ ]

3. EXAMPLE OF INIFINITE WHILE LOOP

Source Code

# define infinite while loop 
# using colon : or true keyword 
while true
do
    echo "Hello World"
done

Output

























Video Demo





Comments

Popular posts from this blog

Vivo V30 Pro 5G

Xiaomi 14 - Features, Price

Oppo F25 Pro 5G Review - Features, Price