Working with FOR Loop in Bash Shell with Examples

Channel: Linux
Abstract: PARAM2 and PARAM3 are parameters passed as an arguments. These parameters can be a number string or file names. For loop will be executed 3 times as p

Loops are very useful for doing repetitive tasks for any programming language. For loops are also available for bash scripting. In this article we will learn about uses of for loops with useful examples.

Syntax: for VARIABLE in PARAM1 PARAM2 PARAM3
do
// commands to execute
done

In above syntax PARAM1, PARAM2 and PARAM3 are parameters passed as an arguments. These parameters can be a number string or file names. For loop will be executed 3 times as per numbers of parameters passed in above syntax. VARIABLE is a variable which is initialized one by one using parameter values.

  • Read: While Loop Examples in Bash Scripting
  • Examples of For Loop in Bash Script

    To define number of number of iteration’s for a loop, we simply pass numbers as an argument for variable.

    for i in 1 2 3 4 5 6
    do
       echo "$i"
    done
    

    We can also define range in place of writing each number on latest version of bash. To define a range we use curly braces like {STARTNUMBER..ENDNUMBER}.

    for i in {1..6}
    do
       echo "$i"
    done
    

    We can also pass string values as parameters for defining number of iterations and pass as argument

    for i in SUN MON TUE WED THU FRI SAT
    do
       echo "This is $i"
    done
    

    We can also pass all the file names as arguments to pass to loop.

    for i in *
    do
       echo "This file is $i"
    done
    
    Creating C Like For Loop in Bash Script

    We can also create C like for loops inside a shell script

    Syntax: for ((EXPR1; EXPR2; EXPR3))
    do
    // commands to execute
    done

    Where EXPR1 is used for initialization, EXPR2 is used for condition and EXPR3 is used for increment/decrement of variable values.

    For example to execute a loop 10 times we can simply write for loops like

    for ((i=1; i<=10; i++))
    do
      echo "$i"
    done
    

    Ref From: tecadmin

    Related articles