Bash 'while' loop - We have been discussing loops in bash scripting and we have covered one of its kinds,
forloop, in our last article - Bash Scripting : 'for' Loops. In that article, we saw that, a loop is required in order to repeat a certain task a number of times. In
forloop syntax, we created a loop using Initialization, Condition and Increment / Decrement. This article is about another kind of loop statement -
whileloop, in which we study its syntax and understand it in more details with examples.
Here we go!
The 'While' Loop
whileloop, we have a condition, which is checked after every iteration. As long as the condition stays True, the block of code keeps executing, thus forming a loop. As soon as the condition becomes False, the loop is terminated. Have a look on
while [ Condition ] do -- Block of Commands -- done
#!/bin/bash n=1 while [ $n -le 5 ] do echo "This is Iteration No. $n" n=$( expr $n + 1 ) done
In above code, we have
n=1before we enter the loop. When we enter the loop, the condition is checked whether
n <= 5, which is True, and we enter the loop. Now,
echostatement displays current value of
nwhich is 1. Then,
nis incremented by 1 (Please check our article on Arithmetic Operations for more details about
expr). When the block ends, we have
n=2and the control goes back to
while, where the condition is checked again. Condition follows,
echoprints the value of
nand increments its value by 1. So, after 5 iterations, we would have
echostatement executed 5 times and with
nincremented to value 6. At this point, control goes to
while, condition is checked and does not follow. Hence the loop exits here. In the end, we have below result in the output.
This is Iteration No. 1 This is Iteration No. 2 This is Iteration No. 3 This is Iteration No. 4 This is Iteration No. 5
An Infinite 'while' Loop
whileloop is the one, which never ends. For this, we need a condition which is always True. So, for this, you can mention any non-zero number or a non-empty string or a
:(or a condition which is always True) as the condition, which is evaluated to True by bash. The condition always being True, the block of code will keep executing infinitely.
#!/bin/bash while [ 1 ] do echo "You are in an Infinite Loop. Press CTRL + C to Exit.." done
#!/bin/bash while : do echo "You are in an Infinite Loop. Press CTRL + C to Exit.." done
#!/bin/bash while [ 5 -eq 5 ] do echo "You are in an Infinite Loop. Press CTRL + C to Exit.." done
breakstatements are used in the loops to exit from the loop prematurely, based on certain condition (Please take look over our article on Bash Conditionals). If the condition follows,
breakstatement is executed, which then prevents further iterations from happening and exits from loop.
while [ condition ] do -- Some Commands -- if [ condition ] then break fi -- More commands -- done
#!/bin/bash while : do echo "Enter a single-digit number :" read n if [ "$n" -gt 9 ] then echo "Wrong Entry! Program will terminate now.." break fi echo "Good!" done
The continue statement in a loop, when certain condition becomes true, skips all the subsequent statements, coming after it, and continues with the next iteration of the loop. So, when a
continuestatement is reached, further portion of code is skipped from execution and next iteration is started.
while [ condition ] do -- Some Commands -- if [ condition ] then continue fi -- More commands -- done
We take an example of printing all even numbers less than 20. In this case, we check whether a number is perfectly divisible by 2, using mod operator. If it is not, its clearly an odd number, so we prefer not to print it and skip further processing. For this, we introduce a
continuestatement in this condition, to prevent odd numbers from printing.
#!/bin/bash i=0 while [ $i -le 20 ] do i=$(expr $i + 1) j=$(expr $i % 2) if [ $j -ne 0 ] then continue fi echo "$i" done
2 4 6 8 10 12 14 16 18 20
Example : Factorial of a Number
Factorial of a number is nothing but product of all natural numbers less or equal to the particular number. With this logic, we initialize a variable
factwith 1. We then keep this value multiplying in each iteration, with the number getting decremented by 1, after every iteration. In the end, we get
n * (n-1) * (n-2) * ... * 1saved in the variable
fact, which is the expected result.
#!bin/bash echo "Enter the Number" read num n=$num fact=1 while [ $num -ge 1 ] do fact=$(expr $fact \* $num) num=$(expr $num - 1) done echo "Factorial( $n ) = $fact"
Enter the Number 6 Factorial( 6 ) = 720
With this, we have come to an end of this discussion on bash
whileloops. In this article, we've learned how
whileare constructed and how the control flow works. We have also revised how
continuestatements work in while loops. In the next article, we will learn about another loop statement -
selectloop. Please share your views and feedback in the comments section below and stay tuned. Thank you.