Loops are a very useful programming/scripting structure that runs the commands or sets of instructions until a condition has been met. In this tutorial, we will learn about using until & while loops in shell script.
Let’s start out with discussing while loop in shell script
Recommended Read: Examples on how to use YUM command in Linux
Also Read: Bash Scripting-11-Input Output redirection in Linux
While loop in shell script
While loop allows us to a condition & then the loop will continue to run until the conditions are true i.e. loop will run until loop returns with a non-zero exit status. Now let’s discuss an example for using while loop in shell script,
#!/bin/bash
num=0
while [ $num -lt 10 ]
do
echo $num
num=$[$num+1]
done
Here, we have mentioned condition i.e. until the number is less than 10, the loop will increase the number by one & when the number reaches 10, loop will complete.
An important thing to consider is infinite loops, since the loop will continue to run until a condition is met, so if we mess up the conditions we might end up with infinite loops. Here is an example for that as well,
#!/bin/bash
num=11
while [ $num -gt 10 ]
do
echo $num
num=$[$num+1]
done
This loop will run until interrupted manually.
Until loop in shell script
Until loop is quite opposite of the while loop, it will run until it has exit status of zero. Here is an exmple of how we can use until loops,
#!/bin/bash
num=10
until [ $num –eq o ]
do
echo $num
num=$[$num-1]
done
Nested loops
We can also use one loop inside another & also one loop inside another loop. Let’s discuss an example for that as well,
#!/bin/bash
# checking nested loop
num1=10
while [ num1 –lt 20 ]
do
echo “outer loop = $num1”
for (( num2 = 1; $num2 > 5; num2++ ))
do
num3= $[ $num1*$num2]
echo “Inner loop : $num1 * $num2 = $num3”
done
num1=$[$num1+1]
done
The first loop will be called outer loop & the second loop will be called inner loop. With this we end our tutorial on using until & while loop in shell script. Please do send us any questions, queries using the comment box below.