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
  • 1. Introduction
  • 2. Iterating over words in a string
  • 3. Loop over a list of strings
  • 4. Iterating using special index variable (@)
  • 5. Using c-style for loops for iteration
  • 6. Iteration over string using a custom delimiter

Using Bash For Loops to Iterate Over a List of Strings

PreviousBash Check Empty ArrayNextBash Break – Using with For Loop

Last updated 1 year ago

1. Introduction

When working with text files or processing text data, very often you will find yourself working with a list of strings. Text processors use looping methods to iterate over the list and access the individual string elements. In this guide, we will learn how to use for loop in bash to iterate over a list of strings.

2. Iterating over words in a string

We can use the for loop to loop through individual words in a string.

See the following example:

#!/bin/bash str="Using for loops for string iteration" for i in $str; do echo "Word: $i";done

We declare a string variable and pass it to for loop using an iterator.

The variable iterates through the string and holds the individual words until no more can be processed.

3. Loop over a list of strings

When working with a list of strings, each string element could either be a single word or multiple space-separated words. Let’s see how we can use for loop in both cases.

3.1 Iterating over string elements in a list

We can use the same for-loop syntax for iterating over a list containing multiple strings.

Example:

#!/bin/bash for i in "Using" "for" "loops" "for" "string iteration"; do echo "String: $i";done

We pass the list of string elements to the for loop using an iterator.

The iterator loops through the list elements and holds the individual string variables. Note that the last element of the list is a multi-word string and the iterator references this entire string.

3.2 Access individual words in a list of multi-word strings

Let’s see how we can use nested loops to access the individual elements in a list containing multi-word strings.

Using the previous example:

#!/bin/bash for i in "Using" "for" "loops" "for" "string iteration"; do for j in $i; do echo "String: $j"; donedone

The outer for loop access the individual elements of the list.

The inner loop iterates over the space-separated words in the list elements.

We see the words “string”, and “iteration” are printed as individual elements in this example.

4. Iterating using special index variable (@)

When working with arrays, we can use the special index variable ‘@’ to iterate over the individual string elements.

4.1 With double quotes

#!/bin/bash declare -a stringArr=("Using" "for" "loops" "for" "string iteration") for i in "${stringArr[@]}"; do echo "String: $i";done

The iterator holds the value of the individual list elements until no more can be processed. If an element is a multi-word string, then the variable references this entire string.

4.2 Without double quotes

In the previous example, we enclosed ${stringArr[@]} in double quotes. When using the double quotes, the iterator references the individual list elements.

Let’s see what happens when we use this syntax without the double quotes.

#!/bin/bash declare -a stringArr=("Using" "for" "loops" "for" "string iteration") for i in ${stringArr[@]}; do echo "String: $i";done

This time we use the ‘@’ index syntax without the double quotes.

Using this syntax, for loop splits the multi-word strings and the individual words can be referenced.

5. Using c-style for loops for iteration

Bash scripting also supports C-Style for loop syntax.

Let’s take an example to understand this further:

#!/bin/bash declare -a stringArr=("Using" "for" "loops" "for" "string iteration")size=${#stringArr[@]} for((i=0; i<$size; i++)); do echo "String: ${stringArr[$i]}"done

We declare an array of strings and store its size in a variable.

In the for loop, we initialize the index variable i = 0 and increment it in the loop as long as i < size of the array.

The individual array elements can be accessed using the array-index referencing syntax.

In the case of multi-word strings, this considers the entire string as a single element. If we want to access the individual words in the string, we need another for loop to iterate over the string.

6. Iteration over string using a custom delimiter

Bash by default considers space (‘ ‘) as a delimiter. If we want to use some other character as a delimiter, it can be controlled by a special shell variable called internal field separator (IFS).

Let’s take an example to understand this further:

#!/bin/bash str="Using-for loops-for-string-iteration-using a-custom delimiter" echo "Before assigning IFS='-'"for i in $str; do echo "String: $i"done IFS='-' echoecho "After assigning IFS='-'"for i in $str; do echo "String: $i"done

We have a string variable that has a few words separated by (‘-’) and a few separated by space (‘ ‘).

Let’s see the output of for loop iterating through this string variable before and after setting the IFS variable.

  • In the first for loop, we have the default value of IFS variable. Thus, Bash treats space as the delimiter.

We declare an and use the for loop to iterate over this array using the special index variable ‘@’.

When IFS to any other character, Bash starts treating it as the delimiter.

After setting IFS=‘-’, Bash based on dash (‘-’) character while considering the space (‘ ‘) separated words as a single element.

array of strings
variable is assigned
splits the string
output of the script using nested loop to access each elements in a list of multi word
c style for loop to access individual array elements of strings
for loop through array using variable @ index without double quotes
output of the script iterate using for loop over a list containing multiple strings
for loop through array using variable @ to iterate individual string elements
output of the script iterate using for loop over words in a string
output of for loop iterating through string variable setting the IFS variable.