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. 

Bash Scripting – For Loop

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

Similar Reads

Simple For loop

To execute a for loop we can write the following syntax:...

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:...

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:...

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....

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....