Similar to the for
command, while
is also the command for loop operations. The command next to while
is evaluated. If it is successful or 0 then the commands inside do
and done
are executed.
The purpose of a loop is to test a certain condition or expression and execute a given command while
the condition is true (while
loop) or until
the condition becomes true (until
loop):
while condition do commands done |
until condition do commands done |
The following is the while_01.sh
script, in which we read a file and display its it's content:
#!/bin/bash file=/etc/resolv.conf while IFS= read -r line # IFS : inter field separator do # echo line is stored in $line echo $line done < "$file"
Let's test the program:
$ chmod +x while_01.sh $ ./while_01.sh
The following will be the output after executing the preceding commands:
nameserver 192.168.168.2 search localdomain
In the following script while_02.sh
, we are printing number 1–10 on the screen using the while
loop:
#!/bin/bash declare -i x x=0 while [ $x -le 10 ] do echo $x x=$((x+1)) done
Let's test the program:
$ chmod +x while_02.sh $ ./while_02.sh
The following will be the output after executing the preceding commands:
0 1 2 3 4 5 6 7 8 9 10
In the following script while_03.sh
, we ask the user to input the test. If the input of the text is quit
, then we terminate the loop; otherwise, we print the text on the screen:
#!/bin/bash INPUT="" while [ "$INPUT" != quit ] do echo "" echo 'Enter a word (quit to exit) : ' read INPUT echo "You typed : $INPUT" done
Let's test the program:
$ chmod +x while_03.sh $ ./while_03.sh
The following will be the output after executing the preceding commands:
Enter a word (quit to exit) : GANESH You typed : GANESH Enter a word (quit to exit) : Naik You typed : Naik Enter a word (quit to exit) : quit You typed : quit
In the following while_04.sh
script, we print the content of variable num
on screen. We are starting with value 1. In the loop, we increment the value of the num
variable by 1. When the value of the variable num
reaches 6, then the while
loop is terminated:
#!/bin/bash num=1 while (( num < 6 )) do echo "The value of num is: $num" (( num = num + 1 )) # let num=num+1 done echo "Done."
Let's test the program:
$ chmod +x while_04.sh $ ./while_04.sh
The following will be the output after executing the preceding commands:
The value of num is: 1 The value of num is: 2 The value of num is: 3 The value of num is: 4 The value of num is: 5 Done.
The while_05.sh
script prints a series of odd numbers on the screen. We are passing a total number of odd numbers required as command-line parameter:
#!/bin/bash count=1 num=1 while [ $count -le $1 ] do echo $num num=`expr $num + 2` count=`expr $count + 1` done
Let's test the program:
$ chmod +x while_05.sh $ ./while_05.sh 5
The following will be the output after executing the preceding commands:
1 3 5 7 9