We earn commission when you buy through affiliate links.
This does not influence our reviews or recommendations.Learn more.
For Loop is an integral part of any programming language.
It allows programs to iterate through a certain number of items.
The first line#!/bin/bashindicates that the code is a bash script.
VAR stands for the temporary variable used For Looping.
N indicates the maximum number of iterations.
do and done start and stop the Loop, respectively.
Actions are the commands that execute within the Loop.
We can execute Bash For Loop with different variables, like list, strings, integers, and arrays.
This article will show a few common examples of the Bash For Loop.
Reading an Array
The syntax for declaring an array is different.
Use parentheses for each element (String).
@ is used to iterate through each element in the array.
We can also use the For Loop to print the indexes and the array elements.
Note that we use !
in the Loop to get the element index.
Iterating Range of Numbers
We can use Bash For Loop to iterate over a range of numbers.
The .. indicates a range of numbers.
We can also skip count numbers by specifying the range.
In the below example, we are skip counting by 3.
The program above starts with 30 as the first number and counts down to 0.
The last parameter in the for loop 3 specifies the skip count number.
Strings and Characters
We can do a lot of interesting string operations with Bash For Loop.
Reading Command-Line Arguments
To read from command-line arguments, we use the read command.
We use the variable total to store the intermediate and final total or sum of the numbers.
Note that we are giving the range as 10 in the above example.
We can change this number to get even and odd numbers between any range.
In this example, we are trying to find the color green.
it’s possible for you to then use the Linux terminal in a similar fashion to CMD.
Next, it’s possible for you to check outhow to run bash scripts using Python.