Monday, 21 December 2015

5 Practical Uses Of While Loop

In this article we will see the basics of while loop and how to use it with logical operators, string and with files. Please go through with the post 15 Practical Uses For Loop In Unix/Linux  for more clarity with loops.

SYNTAX:

 while [ Condition ]
 do
  #--Program logic
 done


Operation on Number:
-lt less than <
-le less than or equal to <=
-gt greater than >
-ge greater than or equal to >=
-ne not equal to !=


Operation on String:
== Equals to
!= Not Equals to


1. How to iterate using while loop.
k=0
while [ $k -lt 4 ]
do
 echo $k
 k=`expr $k + 1`
done


2. How to provide AND and OR condition in while loop.
k=0
m=0
while [[ $k -lt 4 && $m -lt 3 ]]
do
    echo "Value of k is: $k"
    echo "Value of m is: $m"

    k=`expr $k + 1`
    m=`expr $m + 1`
done


Output: Will list down below output, please see double bracket in while condition. When you are using multiple condition provide doube square bracket.
Value of k is:0
Value of m is:0
Value of k is:1
Value of m is:1
Value of k is:2
Value of m is:2


[OR]

k=0
m=0
while [[ $k -lt 4 || $m -lt 3 ]]
do
    echo "Value of k is: $k"
    echo "Value of m is: $m"
    

    k=`expr $k + 1`
    m=`expr $m + 1`
done


Output: Here while has iterated until the value of k becomes 4, irrespective of value of m because of OR (||) condition.
Value of k is: 0
Value of m is: 0
Value of k is: 1
Value of m is: 1
Value of k is: 2
Value of m is: 2
Value of k is: 3
Value of m is: 3


3. How to use while loop with strings
V_User_Name="Unix"
while [ "${V_User_Name}" != "Unix" ]
do
    echo "Welcome ${V_User_Name}"
done


Output: Will not print anything and will come out.

V_User_Name="Unix"
while [ "${V_User_Name}"=="Unix" ]
do
    echo "Welcome ${V_User_Name}"
    break;
done


Output: Will print Welcome Unix.
Please see == sign carefully. there should not be any space between operands and operator.

4. How to execute while in Infinite loop.
while true:
do
 echo "Unix is Great"
done


Output: This while loop will execute indefinitely. To coming out from an infinite loop we can use break statement as used in above scenario.

5. How to read a file using while loop.
while read V_File_Line
do
 echo ${V_File_Line}

done < F_Input_File.txt

Output: Will read the file line by line and display at console. We can build our logic on V_File_Line as per our requirement.
Unix Linux Windows
All are awesome OS

Here,
1. F_Input_File.txt is the file from where we are reading the data/line.
2. read is the keyword.
3. unlike for loop, we need not require to set IFS in case of while loop. While loop internally manage to print the complete line.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...