Bash Scripting
  • scripting list
  • How to Make Bash Script Executable Using Chmod
  • Shell Script to Check Linux Server Health
  • How to Concatenate String Variables in Bash [Join Strings]
  • How to Do Bash Variable Substitution (Parameter Substitution)
  • Bash Parameter Expansion with Cheat Sheet
  • Bash getopts with Examples
  • How to Pass all Arguments in Bash Scripting
  • Bash Function Return Value
  • Bash Loop Through Lines in a File
  • Bash readarray with Examples
  • Bash let with Examples
  • Bash expr with Examples
  • Bash read password
  • Bash for Loop Range Variable
  • Bash Arrays Explained
  • Ways to Find Bash Array Length
  • Bash Split String by Delimiter
  • Bash if Options
  • Bash If Statements for String Comparison
  • Debugging Techniques for Bash Scripts
  • Determining if a Bash String is Empty
  • Bash if Statement with Multiple Conditions
  • Meaning of Shebang in Bash Scripts
  • How to Comment Code in Bash Script
  • How to Read CSV File in Bash
  • Bash Scripting: How to Check if File Exists
  • Bash If Else Statements: Examples and Syntax
  • Bash Scripting: How to Check if Directory Exists
  • Bash eval Command with Examples
  • How to Use Sleep Command in Bash Scripting
  • Bash Associative Arrays with Examples
  • Bash Script for Counting Lines in a File
  • How to Use While Loop in Bash for Efficient Scripting
  • Bash basename Command with Examples
  • How to Create Multiline Strings in Bash
  • How to Use Bash if With && Operator
  • 50 Bash Script Examples to Kickstart Your Learning
  • Case statement in Bash Shell Scripting
  • Trimming White Space in Bash
  • How to Extract Filename from Absolute Path in Bash
  • How to Get Directory Path in Bash
  • Extract Extension from File Path in Bash
  • Extract Filename without Extension from Full Path in Bash
  • Bash for Each File in a Directory
  • Bash for Loop with Array
  • Bash Continue – Using with for Loop
  • Bash Backticks vs Dollar Parentheses $()
  • How to Assign Variable in Bash
  • How to Assign Variable in Bash
  • Bash Division Explained
  • Bash Modulo (Division Remainder)
  • Bash While Read Line by Line
  • Bash shift Command
  • Bash Looping Through Array of Strings
  • Bash read Command with Examples
  • Bash Check Empty Array
  • Using Bash For Loops to Iterate Over a List of Strings
  • Bash Break – Using with For Loop
  • How to Use seq With for Loop in Bash
  • How to Use $@ in Bash Scripting
  • Get the Current Script Directory in Bash
Powered by GitBook
On this page
  • Introduction
  • Iterating using the array elements
  • Iterating using an index variable
  • Looping through nested arrays

Bash for Loop with Array

PreviousBash for Each File in a DirectoryNextBash Continue – Using with for Loop

Last updated 1 year ago

Introduction

In this tutorial, we will cover different methods to iterate over arrays using for loops. Arrays are a powerful data structure in Bash, and by leveraging the flexibility of for loops, we can process each element of an array efficiently. Whether you need to perform computations, concatenate strings, or work with nested arrays, this tutorial will provide you with the necessary tools to iterate over arrays effectively in Bash.

Iterating using the array elements

Bash provides a simple for-loop syntax to iterate over an of items.

#!/bin/bash for i in "${array[@]}";do ## Process $idone

Using this syntax, bash iterates the variable i through the elements of the array one at a time. Within the for loop, we can reference $i to process the i’th element of the array.

Let’s take some examples to understand this:

Array of integers

Let us see how we can iterate over an array to compute the sum of all the numbers.

#!/bin/bash ## Declare an array of integersdeclare -a numbers=(1 2 3 4 5) sum=0 ## Iterating using for loopfor num in "${numbers[@]}"do echo "The number is $num" sum=$((sum+$num))done echo "The sum is $sum"

  • We declare an array of integers, numbers.

  • for num in "${numbers[@]}" iterates the variable num through the elements of numbers until no more elements are left.

  • Within the for loop, we add the individual elements to the sum variable.

It displays each number in the array and calculates their sum, which is 15 in this case.

Array of strings

#!/bin/bash ## Declare an array of stringsdeclare -a stringArr=("Learn" "here" "for" "with" "array") result="" for str in "${stringArr[@]}"do result="$result$str "done echo "The resulting string is: $result"

  • We declare an array of strings, stringArr.

  • for str in "${stringArr[@]}" iterates the variable str through the elements of stringArr until no more elements are left.

  • Within the for loop, we append the individual stringArr elements at the end of the result string.

The script takes the individual elements of the stringArr array and concatenates them into a single string with spaces between each word.

Iterating using an index variable

If you are coming from the C/C++ world, you might recognize this syntax.

#!/bin/bash for ((i=0, i<${len}; i++));do ## Process "${arr[$i]}"done

Let’s take an example to print array variables at each index.

#!/bin/bash ## Declare an array of integersdeclare -a numbers=(10 2 7 8 -1) ## Get the length of the arraylen=${#numbers[@]} for ((i=0; i<$len; i++));do echo "Index: $i, number: ${numbers[$i]}"done

  • We declare an array of integers, numbers and store its size in variable len.

  • We use double parentheses for-loop syntax using the iteration index i which iterates from 0 till (len-1). Within the for loop, we can use index referencing syntax ${numbers[$i]} to process the individual elements.

Looping through nested arrays

Bash does not support multi-dimensional arrays like other programming languages. That means it can store values only on a single level. However, you can iterate through two arrays at a time by using nested for loops.

Example:

#!/bin/bash ## Initialize 2 arrays of integersdeclare -a numbers1=(3 4 1 -1 -2)declare -a numbers2=(2 7 8 9 10) ## Get the length of the arrayslen1=${#numbers1[@]}len2=${#numbers2[@]} for ((i=0; i<$len1; i++)); do for ((j=0; j<$len2; j++)); do echo "Element ($((i+1)), $((j+1))): (${numbers1[$i]}, ${numbers2[$j]})" donedone

  • We declare two arrays, numbers1, and numbers2 and store their sizes in variable len1, len2.

  • We use nested for loops to iterate over the elements of the arrays. Effectively, we can access all the combinations (len1 * len2) of the array elements.

We see 25 different pairs of array elements.

We can also iterate over an using this syntax.

Let’s consider an example to the strings in an array and print the resulting string.

array of strings
concatenate
array
output of a Bash script that calculates the sum of an array of numbers.
displaying the resulting string: 'Learn here for with array' generated from the array ['Learn', 'here', 'for', 'with' 'array']
Output of Bash script displaying elements and positions of two arrays of integers
Bash script output: Index 0, number 10; Index 1, number 2; Index 2, number 7; Index 3, number 8; Index 4, number -1.