Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

UNIX Shell Loop


May 23, 2021 UNIX Getting started


Table of contents


Shell loop

Loops are a powerful programming tool that enables you to repeat a series of commands. There are four types of loops for Shell programmers:

  • While loop
  • For loop
  • The until loop
  • Select loop

Use different loops depending on the situation. F or example, as long as a given condition is still true, the while loop executes the given command. The until loop is not executed until the given condition becomes true.

Once you have good programming practices, you'll start using the appropriate loops as appropriate. While and for loops are implemented in most other programming languages, such as C, C, and PERL.

Nested loops

All loops support the concept of nesting, which means that one loop can be placed in another similar or different loop. This nesting can be up to an unlimited number of times depending on your needs.

Here is an example of a nested while loop, and other loop types can be nested in a similar way based on programming requirements:

Nested while loops

You can use the while loop as part of another while loop body.

Grammar

    while command1 ; # this is loop1, the outer loop
    do
       Statement(s) to be executed if command1 is true

       while command2 ; # this is loop2, the inner loop
       do
      Statement(s) to be executed if command2 is true
       done

       Statement(s) to be executed if command1 is true
    done

Example

Here's a simple example of loop nesting, adding another countdown loop inside the loop to count to nine:

    #!/bin/sh

    a=0
    while [ "$a" -lt 10 ]# this is loop1
    do
       b="$a"
       while [ "$b" -ge 0 ]  # this is loop2
       do
      echo -n "$b "
      b=`expr $b - 1`
       done
       echo
       a=`expr $a + 1`
    done

This will result in the following results. I t is important to note how echo -n works. Here -n allows the output to avoid printing new lines of characters.

    0
    1 0
    2 1 0
    3 2 1 0
    4 3 2 1 0
    5 4 3 2 1 0
    6 5 4 3 2 1 0
    7 6 5 4 3 2 1 0
    8 7 6 5 4 3 2 1 0
    9 8 7 6 5 4 3 2 1 0