Web | This Site

Unix for Beginners
Unix Shell Programming
Advanced Unix
Unix Useful References
Unix Useful Resources
Selected Reading
© 2011 TutorialsPoint.COM

| Home |  | References |  | Discussion Forums |  | About TP

# Unix Shell - The while Loop

The while loop enables you to execute a set of commands repeatedly until some condition occurs. It is usually used when you need to manipulate the value of a variable repeatedly.

## Syntax:

    while command
    do
       Statement(s) to be executed if command is true
    done

Here Shell command is evaluated. If the resulting value is true, given statement(s) are executed. If command is false then no statement would be not executed and program would jump to the next line after done statement.

## Example:

Here is a simple example that uses the while loop to display the numbers zero to nine:

    #!/bin/sh

    a=0

    while [ $a -lt 10 ]
    do
       echo $a
       a=`expr $a + 1`
    done

This will produce following result:

    0
    1
    2
    3
    4
    5
    6
    7
    8
    9

Each time this loop executes, the variable a is checked to see whether it has a value that is less than 10. If the value of a is less than 10, this test condition has an exit status of 0. In this case, the current value of a is displayed and then a is incremented by 1.

Advertisement

Online Image Processing

Indian Baby Names