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
  • Looping over arrays
  • Conclusion

Bash Looping Through Array of Strings

PreviousBash shift CommandNextBash read Command with Examples

Last updated 1 year ago

An array is a data structure consisting of a collection of items holding some data. Every element of the array is identified by an array index. The elements can be computed from the array index. Looping through the arrays allows us to learn what is stored in each element for further processing.

Available loops in bash

Loops are constructs that we use to execute a sequence of events until a specific condition is met. Bash provides us with three loops to iterate over the array elements. They are:

  • while

  • for

  • until

Looping over arrays

Generally, arrays are coupled with loops. The iteration statements are useful to automate tasks that require retrieving the contents of the array. There are multiple ways to iterate over the arrays.

Using for loop to iterate over each element

We can loop through arrays in bash using for loop as follows:

#!/bin/basharr=(a b c d e)for i in "${arr[@]}"do echo "$i"done

We have considered an array comprising five elements. We use the Bash for loop to iterate over the items of this array. Every element of the array is referred directly rather than the index

In the first iteration of the for loop the first element 'a' is stored in i and printed. The program then moves to the next element and 'b' is printed. This goes on and prints till 'e' after which the loop finishes

Iterating using the index of the elements

We can also loop through arrays using the index of the elements:

#!/bin/basharr=(a b c d e)for (( i=0; i<${#arr[@]}; i++ ))do echo ${arr[$i]}done

We know the index values are in sequence and begin from zero. Hence, we increment the iterator value in the for loop until the length of the array. During each iteration, we then refer to the array at that index to access the item.

In the first iteration of the for loop the first element arr[0] 'a' is referenced by the iterator at the 0th index and printed. The program then moves to the next element which is arr [1] and 'b' is printed. This goes on and prints till the last index arr[4] and 'e' after which the loop finishes.

Using a while loop

We can also use the while loop to iterate over the array elements as we did above.

#!/bin/basharr=(a b c d e)i=0while [ $i -lt ${#arr[@]} ]do echo "${arr[$i]}" i=$((i + 1))done

We again use the unique property of the array since the indexes are in progression. However, we have taken the while loop instead of the for loop. In this case, too, we increment the index value of the iterator in the while loop. This loop keeps running until the value of the iterator is less than the length of the array. During each iteration, we then refer to the array at that index to access the item. The loop terminates once the iterator value becomes greater than the array length.

In the first iteration of the loop the first element arr[0] 'a' is printed. The program then moves to the next element which is arr [1] and 'b' is printed. This goes on and prints till the last index arr[4] and 'e' after which the loop finishes.

Using an until loop

Just like we described for and while loop, we can also use the until loop to read the array elements.

#!/bin/basharr=(a b c d e)i=0until [ $i -ge ${#arr[@]} ]do echo "${arr[$i]}" i=$((i + 1))done

We can also use the until loop in the same manner as the while loop. We increment the index value of the iterator in the until loop. The loop keeps running till the iterator value is lesser than the array length. In every iteration, we then point to the array at that index to access the item.

In the first iteration of the loop the first element arr[0] 'a' is printed. The program then moves to the next element which is arr [1] and 'b' is printed. This goes on and prints till the last index arr[4] and 'e' after which the loop finishes.

Using loops with numerical condition

We can also use the while loop to iterate over the array elements as we did above.

#!/bin/basharr=(a b c d e)i=0echo "Using while loop"while (( $i < ${#arr[@]} ))do echo "${arr[$i]}" i=$((i + 1))done i=0echo "Using until loop"until (( $i >= ${#arr[@]} ))do echo "${arr[$i]}" i=$((i + 1))done

We have called upon the while as well as the until loop. The evaluation of the condition is done by the double parentheses (()). Inside this, the expression has comparison operators to numerically compare the length of the array against the current position of the iterator.

In the first iteration of the for loop the first element arr[0] 'a' is referenced and printed. The program then moves to the next element which is arr [1] and 'b' is printed. This goes on and prints till the last index arr[4] and 'e' after which the loop finishes.

Reading multiple arrays together

Bash also gives us the option to read more than one array in the same loop.

#!/bin/basharr1=(a b c d e)arr2=(z y x w v)for (( i=0; i<${#arr1[@]}; i++ ))do echo ${arr1[$i]} ${arr2[$i]}done

We have taken two arrays with the same length and can use any of the methods which we have used so far. We increment the iterator value in the for loop until the length of the array. During each iteration, we then refer to both the array’s at that index to access their items.

In the first iteration of the loop, the first element arr1[0] 'a' and arr2[0] 'z' are referenced by the iterator at the zeroth position and they are printed. This goes on and prints till the last index of the array after which the loop finishes.

Conclusion

  • Bash provides us with multiple ways of looping through the arrays.

  • For, while and until loops can be used to read the array elements.

  • Array elements can be read by their positions as they are present in contiguous locations.

Iterating using the index
using until loop with array
for loop iterate with an array
loops with comparison operators
for loop with multiple arrays
while loop with array