Javatpoint Logo
Javatpoint Logo

Shell Scripting for loop

The for loop moves through a specified list of values until the list is exhausted.

1) Syntax:

Syntax of for loop using in and list of values is shown below. This for loop contains a number of variables in the list and will execute for each item in the list. For example, if there are 10 variables in the list, then loop will execute ten times and value will be stored in varname.

Shell scripting For loops 1

Look at the above syntax:

  • Keywords are for, in, do, done
  • List is a list of variables which are separated by spaces. If list is not mentioned in the for statement, then it takes the positional parameter value that were passed into the shell.
  • Varname is any variable assumed by the user.

Example for:

We have shown an example to count 2's table within for loop.

Shellscripting For loops 2

Look at the above snapshot, our varname is table, list is specified under curly braces. Within the curly braces, first two will initialize the table from 2, 20 represents maximum value of $table and last 2 shows the increment by value 2.

Shellscripting For loops 3

Look at the above snapshot, it displays the 2's table as the output.

2) Syntax:

Syntax of for like C programming language.

Shellscripting For loops 4

Look at the above snapshot, condition1 indicates initialization, cond2 indicates condition and cond3 indicates updation.

Example for:

We have shown an example to count the number in reverse direction.

Shellscripting For loops 5

Look at the above snapshot, this is the loop script. $i will initialize with 10 and will go till 1, decrementing with 1 value.

Shellscripting For loops 6

Look at the above snapshot, this is the output of the script.

Next TopicWhile loop

Please Share

facebook twitter google plus pinterest tumbler

Latest 4 Tutorials