Hello Linux-fanatics, In our last tutorial we learned to use READ command to take user's Input & also learned to redirect output of a script to a file. In this tutorial we will be discussing WHILE & UNTIL loop commands.
WHILE loop command
While loop allows us to define a command/condition & then it keeps the condition in loop until loop returns with a non-zero exit status.
Syntax for using while loop
Conditions/parameters used with while command are same as used with if-then statements.
This script keeps on printing value for $num1 up until value is less than 10 i.e. upto 9. As soon as it reaches to 10 loop completes & will stop.
NOTE:- Very important thing to consider when using loops is that you are not stuck in infinite loops. Change num1=$[$num1+1] to num1=$[$num1-1] & you will understand what I mean. If you are stuck in one such loop, press ‘ctrl+C’ to get out of it & always be cautious when using loops.
Until command is just opposite of while command. Until loop runs until it has exit status of zero.
Syntax for until command is same as while command i.e.
We can use one loop inside the other loop, if needed. First loop used is called outer loop & the loop inside the outer loop is called inner loop.
Reading data from a file
We can also read data from a file as input for variables in the script. Let’s create a script doing just that,
Create a file named “hobbies.txt” in /home/dan with following content
Dan: loves football
Susan: loves table-tennis
Daniel: loves sleeping
Now, we will write a script to read the content of this file as input values for our variables
Let’s elaborate what the script means,
IFS.OLD=$IFS is used when & if we need to restore old values of IFS (Internal field seperator)
Next, IFS=$’’\n’ means , now only new line will be a separator
Then, we declared ”hobbies” as variables which will take data from text file,
And then we printed values of our variable “hobbies” in outer loop & then with ":" as separator , we printed “hobbies” values one after another in separate lines.
This ends our tutorial. Next up, we will discuss “how we can control our loops by using break & continue commands”
Also, mention you r queries/comments down below.ADIOS!!!