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
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,
while [ $num -lt 10 ]
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,
while [ $num -gt 10 ]
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,
until [ $num –eq o ]
We can also use one loop inside another & also one loop inside another loop. Let’s discuss an example for that as well,
# checking nested loop
while [ num1 –lt 20 ]
echo “outer loop = $num1”
for (( num2 = 1; $num2 > 5; num2++ ))
num3= $[ $num1*$num2]
echo “Inner loop : $num1 * $num2 = $num3”
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.