Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

unix
linux
shell

How to implement shell loops in UNIX/Linux

Syed Muhammad Ali Mustafa

What are loops?

Loops are programming structures that repeat a block of program statements until a given condition is met.

Loops in UNIX/Linux

There are three types of shell loops in UNIX/Linux:

  • for loop
  • while loop
  • until loop

for loop

The for loop operates on a list of items. The statements in the for loop are executed for all items in the list. The for loop is initialized as follows:

for var in word1 word2 ... wordN
do
   Statement(s) to be executed
done

Flowchart

Code

The code below demonstrates the use of the for loop.

for a in 10 8 6 4 2
do
  echo $a # print a
done

In first iteration of the loop, var will be assigned the first value in the list10. In the second iteration, var = 8. In the third iteration, var = 6, and so on.

while loop

The statements in the while loop are executed until the command in the condition becomes false. The while loop is initialized as follows:

while command
do
     Statement(s) to be executed
done

Flowchart

Code

The code below demonstrates the use of the while loop.

a=10

while [ $a -gt 0 ]   # a > 0
do
   echo $a  # print a
   a=`expr $a - 2`   # a = a - 1
done

until loop

The statements in the until loop are not executed until the command in the condition becomes true. The until loop is initialized as follows:

until command
do
     Statement(s) to be executed
done

Flowchart

Code

The code below demonstrates the use of the until loop.

a=10

until [ $a -lt 2 ]   # a < 2
do
   echo $a  # print a
   a=`expr $a - 2`   # a = a - 1
done

A variable (a) is initialized with a = 10 in line 1. The until loop in line 3 executes until the condition (a < 2) is false. When a < 2 becomes true, the loop breaks.

RELATED TAGS

unix
linux
shell

CONTRIBUTOR

Syed Muhammad Ali Mustafa
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring