1. Home
  2. Bash
  3. Bash Tutorial
  4. Bash – For Loop

Bash – For Loop

For Loop in Bash

In a programming language, a loop is used to repeat the execution of a block of code until the satisfied defined condition. Which is helpful to perform repetitive tasks. Mainly there are 3 types of loops, for, do, and do-while. In this tutorial, we will discuss for loop in shell scripting.

The shell scripting also provides for loops to perform repetitive tasks. A basic for loop syntax looks like:

Syntax:

for VARIABLE in PARAM1 PARAM2 PARAM3
do
  //for-loop statements
done 

The for loop executes for all the defined parameters once. Loop scope is started with a keyword “do” and ended with another keyword “done”. All the statements must be written inside the scope of the loop.

As per the syntax, VARIABLE is initialized with the parameter’s value which can be accessed inside the for loop scope. These parameters can be any number, string, etc.

#1. Bash – For Loop Example

Check below basic for loop which iterates 5 times.

You can also define a range with for loop in the bash script with numeric values.

The arguments can be also a string like:

#2. Bash – For Loop in C Style

You can also write for loop in bash script similar to for loop in c programming. For example to print 1 to 10 numbers.

#3. Bash – For Loop with Files

You can access filenames one by one in for loop under the specified directory. For example, read all files from the current directory.

The above loop will iterate the number of times as the number of files available. It will select one by file in each iteration.

Tags , , , ,