A loop is a program that has powerful features, allowing you to repeat a set of commands. In this chapter, you will learn through practical examples of loops contained in shell programs.

  1. While loop
  2. For loop
  3. Until loop
  4. Loop select

You will use different loops based on different situations. For example, the while loop will run the command until the given condition remains true, while the until loop will run until the given condition becomes true.

Once you have good program exercises, you will start using the appropriate loop based on the given situation. Here, while and for loops are available in most other program languages ​​such as C, C ++ and PERL etc.

Insert loops in Unix / Linux

All loops support nested concepts, which means you can put a loop inside a similar loop or other loops. This nesting may not limit the maximum number of loops, it depends on your requirements.

Here's an example of nesting a while loop, and in the same way, other loops can be nested according to program requirements.

Insert the while loop in Unix / Linux

It is possible to use a while loop as part of the body of another while loop.

Syntax:

 while command1 ; # Day is a big loss, a lot of money is left due to the fact that the command1 is true while command2 ; # Day is dead long, it is dead in the game because of the command of the command2 is true done 

For example:

The following is a simple example of loop nesting:

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

It produces the following result. It is important to remember how echo -n works here. Here -n option allows echo to avoid printing a new character line.

 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 

According to Tutorialspoint

Last lesson: Flow control in Shell

Next lesson: Loop control in Unix / Linux

5 ★ | 1 Vote | 👨 197 Views

Above is an article about: "Loop in Unix / Linux". Hope this article is useful to you. Don't forget to rate the article, like and share this article with your friends and relatives. Good luck!

« PREV POST
NEXT POST »