How to use while loop in the shell script

How to use while loop in the shell script

In this article, we will see how to use while loop in the shell script.

The while loop enables you to execute a set of commands repeatedly until some condition occurs. It is usually used when you need to manipulate the value of a variable repeatedly.



Syntax:

while command
do
   Statement(s) to be executed if command is true
done

Here the Shell command is evaluated. If the resulting value is true, the given statement(s) are executed. If the command is false then no statement will be executed and the program will jump to the next line after the done statement.





#! /bin/bash
#first while loop (loop are command which is used repeatly while loop). if condition is true then while loops work

while [ condition ]
do
     command1
     command2
     command3
done


Example:

n=1
while [ $n -le 5 ]
do
      echo "$n"
      (( n++ ))
done

Example:

n=6
while [ $n -le 8 ]
do
      if [ $n -le 10 ]
then
       echo "condition is true"
else
        echo "condtion is false"
fi
       echo "$n"
        n=$(( n+1 ))
done

#sleep command during while loop to give some second time to go next step

n=1
while [ $n -le 2 ]
do
     echo "$n"
     (( n++ ))
     sleep 1
done





Example:

n=1
while [ $n -le 3 ]
do
      echo "$n"
      (( n++ ))
done

Share:

0 comments

Please leave your comments...... Thanks