Bash Scripting - For Loop
Last Updated :
15 Sep, 2023
Since BASH is a command-line language, we get some pretty feature-rich experience to leverage the programming skills to perform tasks in the terminal. We can use loops and conditional statements in BASH scripts to perform some repetitive and tricky problems in a simple programmatic way. In this article, we are going to focus on the for loop in BASH scripts.
Depending on the use case and the problem it is trying to automate, there are a couple of ways to use loops.
- Simple For loop
- Range-based for loop
- Array iteration for loops
- C-Styled for loops
- Infinite for loop
Simple For loop
To execute a for loop we can write the following syntax:
#!/bin/bash
for n in a b c;
do
echo $n
done
- In the first iteration,
n
takes the value "a", and the script prints "a". - In the second iteration,
n
takes the value "b", and the script prints "b". - In the third iteration,
n
takes the value "c", and the script prints "c".

The above command will iterate over the specified elements after the in keyword one by one. The elements can be numbers, strings, or other forms of data.
Range-based for loop
We can use range-based for loops. In this type of loop, we can specify the number to start, to stop, and to increment at every iteration(optional) in the statement. There are two ways you can do this i.e. by mentioning the increment/decrementer value and by incrementing by one by default. The syntax looks like this:
#!/bin/bash
for n in {1..5};
do
echo $n
done

In the above code, we use the "{}" to specify a range of numbers. Inside the curly braces, we specify the start point followed by two dots and an endpoint. By default, it increments by one. Hence we print 5 numbers from 1 to 5 both inclusive.
#!/bin/bash
for n in {1..5..2};
do
echo $n
done

Here we can see that the loop incremented by 2 units as mentioned in the curly braces. Thus, this makes working with numbers very easy and convenient. This can also be used with alphabetical characters.
NOTE: We cannot use variables inside the curly braces, so we will have to hardcode the values. To use the variables, we see the traditional C-styled for loops in the next few sections.
Array iteration for loops
We can iterate over arrays conveniently in bash using for loops with a specific syntax. We can use the special variables in BASH i.e @ to access all the elements in the array. Let's look at the code:
#!/bin/bash
s=("football" "cricket" "hockey")
for n in ${s[@]};
do
echo $n
done

We can iterate over the array elements using the @ operator that gets all the elements in the array. Thus using the for loop we iterate over them one by one. We use the variable ${variable_name[@]} in which, the curly braces here expand the value of the variable "s" here which is an array of strings. Using the [@] operator we access all the elements and thus iterate over them in the for a loop. Here, the "n" is the iterator hence, we can print the value or do the required processing on it.
C-Styled for loops
As said earlier, we need to use the variables inside the for loops to iterate over a range of elements. And thus, the C-styled for loops play a very important role. Let's see how we use them.
#!/bin/bash
n=7
for (( i=1 ; i<=$n ; i++ ));
do
echo $i
done

As we can see we can dynamically use the value of the range of end conditions. Remember the spaces between the double braces might be intentional and are part of the syntax. C-styled for loops are the loops that have 3 parts, the initializing iterator, the incrementor/decrementer, and the end condition.
In the syntax above, we have initialized the loop iterator/counter to 1 that can be anything as per choice. The second part is the end condition, here we have used the variable "n" which is initialized before the for loop and thus we use the simple $ operator to get the value of the variable. Finally, we have the incrementor/decrementer which changes the iterator/counter to a value that can be anything but, in the example, we have used the unary operator (++) to increment the value by one which is equivalent to "i=i+1". Thus we can use statements like i+=2, i--,++i, and so on and so forth.
Infinite for loop
We don't use this often but it is sometimes useful to get certain things working. The syntax is quite easy and similar to the C-styled for loops.
#!/bin/bash
n=4
for (( ; ; ));
do
if [ $n -eq 9 ];then
break
fi
echo $n
((n=n+1))
done
The loop starts with n
set to 4. It increments n
by 1 at each iteration and prints the value of n
until n
becomes equal to 9. When n
reaches 9, the break
statement is executed, and the loop terminates. The script stops after printing the numbers 4 to 8.

As we can see the `for` loop has no conditions and this loops forever but we have a condition statement to check that it doesn't go on forever. We use the break statement inside the if statement so as to get out of the loop and stop iterating with the iterator. We have used the incrementor to increment the variable in the loop otherwise the loop is infinite. Of course, we need some logic to break out of the loop and that is why we need to use the if conditional statement.
Similar Reads
Bash Scripting - Until Loop 'Bash' provides several looping constructs to control the execution flow in scripts, including 'for', 'while', and 'until' loops. The 'until' loop is a unique looping mechanism that runs a block of code repeatedly until a specified condition becomes true. It essentially works in the opposite manner
7 min read
Bash Scripting - While Loop A while loop is a statement that iterates over a block of code till the condition specified is evaluated to false. We can use this statement or loop in our program when do not know how many times the condition is going to evaluate to true before evaluating to false. Â Table of Content The Syntax of
15+ min read
Bash Scripting - File Extension Bash scripting is a powerful tool for automating tasks and working with files in the command line. One important aspect of working with files in bash is understanding how to handle file extensions. In bash, a file extension is the portion of a file name that follows the last period (.) in the file n
6 min read
Bash Scripting - Array Arrays are important concepts in programming or scripting. Arrays allow us to store and retrieve elements in a list form which can be used for certain tasks. In bash, we also have arrays that help us in creating scripts in the command line for storing data in a list format. In this article, we will
7 min read
Bash Scripting - String Bash String is a data type similar to integer or boolean. It is generally used to represent text. It is a string of characters that may also contain numbers enclosed within double or single quotes. Example: "geeksforgeeks", "Geeks for Geeks" or "23690" are strings Creating a String A basic declarati
2 min read
Solidity For Loop This is the most compact way of looping. It takes three arguments separated by a semi-colon to run. The for loop includes three most important parts: Loop Initialization: The first one is 'loop initialization' where the iterator is initialized with starting value, this statement is executed before t
2 min read
Batch Script - Strings A Bash script is a plain text file. This file contains different commands for step-by-step execution. These commands can be written directly into the command line but from a re-usability perceptive it is useful to store all of the inter-related commands for a specific task in a single file. We can u
4 min read
Swift - For-in Loop The for-in loop in Swift is very similar to for loop in Python. In Python, we write for iteration in range(). Here iteration is just a variable for iteration. In swift, also we write for iteration in range. We have collections like sets, arrays, dictionaries, so we can iterate their items using a fo
6 min read
SAP ABAP | Loop Control Introduction to Loop Control in SAP ABAPIn SAP ABAP programming, loop control is an esseÂntial concept that allows you to execute a block of code multiple times. This is eÂspecially useful when proceÂssing data in an efficient manner. Loops help automate repetitive tasks and handle large datasets
4 min read
For loop Syntax For loop is a control flow statement in programming that allows you to execute a block of code repeatedly based on a specified condition. It is commonly used when you know how many times you want to execute a block of code. For loop Syntax Table of Content For loop Syntax in C/C++For loop Syntax in
5 min read