}

Bash: How to use loops?

Created:

Introduction

Loops in programming must have concept you must learn and it will help you to solve several problems. When using bash, sometimes it's common the need to iterate elements. With bash you can use the "for" statement to do repeat operation over some collection os elements.

Syntax

In general the for has the following syntax:

for VAR in ELEMENTS do # BODY done

On body you will put bash code that will execute operations.

For statement allows you to iterate over different collections, as an example check the next three posibilities:

  • for VARIABLE in 1 2 3 4 5 .. N
  • for VARIABLE in file1 file2 file3
  • for OUTPUT in $(Linux-Or-Unix-Command-Here)

On the first one we iterate over a range of number, on the second one over files and the last one on the ouput.

As an example, suppose we want to echo a messahe 10 times:

    #!/bin/bash
    for i in 1 2 3 4 5 6 7 8 9 10
    do
       echo "Tutorials Technology!!"
    done  

To improve the previous code and avoid writing the whole range of number you can use {1..10}. With the {} syntax you can also specify the steps, for example {0..10..2} will incremente by two on every iteration instead of one.

Looping similar to C code

Bash also support a syntax very similar to C. The example above can be written like this:

    #!/bin/bash
    for (( c=1; c<=10; c++ ))
    do  
       echo "Tutorials Technology!!"
    done  

The above bash code is the same as doing a range. However this particular syntax is more flexible and allow you to iterate in different ways.

True loop or non ending loops

Sometimes writing an infinite or non ending loop could not make sense, however in some problems you will need to do it (for example when you need to do polling).

bash #!/bin/bash $counter = 0 for (( ; ; )) do echo "Tutorials Technology!! $counter" ((counter++)) if [ $counter = 11 ]; then break fi done

The code above will stop the "non-ending" loop when it reaches ten echoes.

You can also use continue which skips the current iteracion.