Unix Shell Loop Types: Do While Loop, For Loop, Until Loop in Unix

By Vijay

By Vijay

I'm Vijay, and I've been working on this blog for the past 20+ years! I’ve been in the IT industry for more than 20 years now. I completed my graduation in B.E. Computer Science from a reputed Pune university and then started my career in…

Learn about our editorial policies.
Updated March 9, 2024

Overview of Unix Shell Loops and Different Loop Types like:

  • Unix Do While Loop
  • Unix For Loop
  • Unix Until Loop

In this tutorial, we will cover the control instructions that are used to iterate a set of commands over a series of data. 

Unix Shell Loops

Unix offers three loop structures of which we can repeat a part of a program at a specified number of times.

Unix Video #17:

Loops in Unix

You may use different loops based on the situation.

They are:

#1) Unix For loop statement

Example: This program will add 1+2+3+4+5 and the result will be 15

for i in 1 2 3 4 5
 do
 sum=`expr $sum + $i`
 done
 echo $sum

#2) Unix While loop statement

Example: This program will print the value of ‘a’ five times, from 1 to 5.

a=1
 while [ $a -le 5 ]
 do
 echo “value of a=” $a
 a=`expr $a + 1`
 done

#3) Unix Until loop statement

This program will print the value of ‘a’ two times from 1 to 2.

a=1
 until [ $a -ge 3 ]
 do
 echo “value of a=” $a
 a=`expr $a + 1`
 done

While running these loops, there may be a need to break out of the loop in some condition before completing all the iterations or to restart the loop before completing the remaining statements. This can be achieved with the ‘break’ and ‘continue’ statements.

The following program illustrates the ‘break’ operation:

 num=1
 while [ $num -le 5 ]
 do
 read var
 if [ $var -lt 0 ]
 then
 break
 fi
 num=`expr $num + 1`
 done
 echo “The loop breaks for negative numbers”

Our upcoming tutorial will brief you more about working with Functions in Unix.

PREV Tutorial | NEXT Tutorial

Was this helpful?

Thanks for your feedback!

Leave a Comment