How to Iterate Through List Using “for” Loop in Bash

Loops are the backbone of task automation in Bash scripting. They allow your scripts to perform repetitive actions on a set of data, saving you time and effort. Among the various loop constructs available in Bash, the for loop reigns supreme for iterating over lists. Its intuitive syntax and flexibility make it a versatile tool for manipulating data and performing repetitive tasks. This article will explore how you can use the “for loop” to list words or phrases from the string list in Bash.

8 Cases of Using “for” Loop in List Iteration in Bash

In this article, I will go through 8 practical cases of utilizing loops with lists, ranging from basic string iteration to advanced techniques like retrieving strings from files, accessing individual words in multi-word elements, and processing multiple arrays simultaneously. These techniques showcase the flexibility of Bash for loops in handling and processing individual words within strings, providing a powerful tool for string manipulation and analysis in your scripts.

1. Iterating Over Words Using “for” Loop

In Bash scripting, the “for loop” extends its versatility to efficiently iterate over words within a string. The syntax for variable in word1 word2 ... wordN allows efficient iteration over words in a string. The following two examples illustrate this concept, echoing each word in the provided string:

#!/bin/bash

for word in Linux is a free, open-source operating system 
do 
echo "Word: $word" 
done
EXPLANATION

This script utilizes a “for loop” to iterate over each space-separated word in the string “Linux is a free, open-source operating system”. During each iteration, the variable ‘word’ takes on each word’s value, and the echo command prints each word with a preset message ‘Word’ before that. So as a result all word in the sentence is printed out in a separate line.

#!/bin/bash

sentence="Linux is a free, open-source operating system"

for word in $sentence
do
echo "Word: $word"
done
EXPLANATION

This script behaves similarly to the previous example. The only difference is this script uses a variable ‘sentence’ to store the entire string and afterward in the “for loop” the string is split into words based on spaces.

Iterating Over Strings Using “for” Loop in bash

The output shows the string is divided into words using “for loop” based on spaces. Each word is echoed with the “Word:” prefix.

2. Loop Through String List in Bash

Whether you are iterating through individual words in a multi-word string or accessing each string from a string list using a “for loop” understanding the syntax is essential for efficient bash scripting. This section will go over those processes using a simple “for loop”.

A. Looping Through String Elements

In Bash scripting, the “for loop” is a versatile tool. It is used for numeric ranges and iterating over elements within a list of strings. The syntax for variable in element1 element2 ... elementN facilitates seamless iteration. This example demonstrates the effective loop over a list of strings, where each string element is processed individually.

#!/bin/bash

for str in "Linux" "is a free" "open-source" "operating system"
do
echo "String: $str";
done
EXPLANATION

This script uses a “for loop” to iterate over a list of strings. The loop processes each string separately, and during each iteration, the variable str represents one of the specified strings. The echo command then prints each string with the prefixed message ‘String‘.

Looping Through String Elements in bash scripting

The output shows that all string in the list is echoed in a separate line.

B. Extract Words From a Multiword String List

In bash scripting, extracting individual words from a list of multi-word strings is a common operation. This task can be easily accomplished by using nested for loops. The outer loop iterates through each multi-word string in the list, while the inner loop breaks down the string into individual words. The following script gives a proper example of this idea:

#!/bin/bash

for str in "Linux" "is a free" "open-source" "operating system"
do
for word in $str
do
echo "Word: $word"
done
done
EXPLANATION

This Bash script utilizes nested for loops to iterate over a list of strings and then over each word within those strings. The outer loop iterates over the list of strings, assigning each string to the variable str. The inner loop processes each word within the current string, and the echo command prints each word with the prefixed message ‘Word’.

Extract Words From a Multiword String List using for loop

Here each word in the list of strings is echoed in a separate line.

3. Parameter Expansion in “for” Loop

Parameter expansion in Bash refers to the process of manipulating or extracting values from variables by using special symbols or operators. It allows you to perform various operations on the values stored in variables. The common syntax for parameter expansion is ${variable}, where the variable is the name of the variable you want to expand.

A. With Double Quotes

The special index variable “@” provides a convenient way to iterate over elements within a list. This parameter expansion technique ensures the correct way of handling spaces in a multi-word phrase. Using the syntax for variable in “${array[@]}” the following example demonstrates a seamless iteration over a list of string phrases. The usage of double quotes is necessary to preserve the integrity of each string phrase.

#!/bin/bash

stringPhrases=("Linux" "is a free" "open-source" "operating system")

for str in "${stringPhrases[@]}" # or you can use “${stringPhrases[*]}”
do
echo "String: $str";
done
EXPLANATION

This script initializes an array stringPhrases with four elements, each containing a different string. The “for loop” iterates over the elements of the array, assigning each string to the variable str. During each iteration, the echo command prints each string with the prefixed message ‘String’. Parameter expansion is used using [@] to ensure that each element of the array is treated as a separate item during iteration.

Parameter Expansion With Double Quotes

With double quotes, parameter expansion echoes each string in a separate line.

Note: ${stringPhrases[*]} works in a similar manner as ${stringPhrases[@]}. So you can use for str in "${stringPhrases[*]}" instead of for str in "${stringPhrases[@]}" but in general using the later one is recommended.

B. Without Double Quotes

In Bash scripting, parameter expansion without double quotes offers a method to extract individual words from a list of multi-word strings. Using the syntax for variable in ${array[@]} will allow the straightforward extraction and processing of individual words. Here’s how:

#!/bin/bash

stringPhrases=("Linux" "is a free" "open-source" "operating system")

for word in ${stringPhrases[@]} # or you can use ${stringPhrases[*]}
do
echo "Word: $word"
done
EXPLANATION

This Bash script begins by creating a stringPhrases array with four different strings. It then uses a “for loop” to go through each string in the array, treating each one as a word. The variable word takes on the value of each string during the loop, and the script prints out each word with the label “Word”. Using [@] ensures that each string in the array is considered separately during the iteration.

Parameter Expansion Without Double Quotes

Without double quotes, parameter expansion echoes each word of each string in a separate line.

Note: You can also declare an array using declare -a stringArr=("Using" "for" "loops" "for" "string iteration"). But for simple loop iteration, it is not necessary.

4. C Styled “for” Loop for String Iteration in Bash

In Bash scripting, the C-style “for loop” presents a structured and familiar approach to iteration. This technique proves useful when dealing with arrays, providing explicit control over the loop’s initialization, condition, and iteration expressions. The following example uses a C-style “for loop” to iterate through the stringPhrases array:

#!/bin/bash

stringPhrases=("Linux" "is a free" "open-source" "operating system")

len=${#stringPhrases[@]}

for((i=0; i<$len; i++))
do
echo "String: ${stringPhrases[$i]}"
done
EXPLANATION

This script ensures individual processing of each string in the array using a C-styled “for loop”. It starts by forming an array named stringPhrases with four distinct strings. The length of the array is determined using the variable len. Then it uses a C-style “for loop” to iterate through each element of the array using the index variable i. Within each iteration, the script prints the current string with the label “String”.

C Styled “for” Loop for String Iteration in Bash scripting

This C-styled “for loop” echoes the string from the list.

5. Looping Through the String Using a User-defined Separator

In Bash scripting, iterating through a string with a user-defined separator involves breaking the string into segments using a specified delimiter. Internal Field Separator (IFS) is a special variable used to determine the delimiter that separates the words in a string. By default, IFS is set to whitespace (space, tab, and newline), but it can be customized to any character or set of characters to define the boundaries between strings.

In the following example, a custom delimiter is used to iterate through the ‘sentence’ string:

#!/bin/bash

sentence="Linux-is a free-open-source-operating system"

DEFAULT_IFS="$IFS"
IFS='-'

for str in $sentence
do
echo "String: $str"
done

IFS=$DEFAULT_IFS
EXPLANATION

This script effectively processes and prints each word in the hyphen-separated string.

It starts by defining a string named sentence containing hyphen-separated words. It temporarily changes the Internal Field Separator (IFS) to the hyphen(-). Then, using a “for loop”, it iterates through the words in the sentence. During each iteration, it prints the current word with the label “String”. After the loop, it restores the original IFS.

Looping Through the String Using a User-defined Separator

Here, the main string is divided into small pieces based on the hyphen(-) location.

6. Reading String List From File

While working with bash scripting there may be cases when you need to extract data from a file. The following example demonstrates the process of fetching a list of strings from a file named list.txt. Each line in the file represents a distinct string, and a “for loop” is used to iterate through these strings.

list.txt file contains the following text :

Linux
is a free
open-source
operating system

Bash script to read the strings from a file:

#!/bin/bash

# File containing the list of strings
file="list.txt"

for line in $(cat "$file")
do
echo "Word: $line"
done
EXPLANATION

This script reads and displays each string from the specified file. It starts by specifying a file named “list.txt” containing a list of strings. It then uses a “for loop” to iterate through each line in the file. During each iteration, the script echoes the current line with the label “Word”.

Reading String List From File using for loop

Here, from the text file, each word is echoed in a separate line.

7. List Multiple Arrays of Strings Together

In Bash scripting, there are scenarios where you may need to read and process multiple string arrays simultaneously. The following example demonstrates the task of combining two string arrays, stringPhrases_1 and stringPhrases_2, into a single array named combinedStringPhrases. Then, a nested “for loop” is used to iterate through the combined array, extracting and echoing each string:

#!/bin/bash

stringPhrases_1=("Linux" "is a free")
stringPhrases_2=("open-source" "operating system")

combinedStringPhrases=("${stringPhrases_1[@]}" "${stringPhrases_2[@]}")

for phrase in "${combinedStringPhrases[@]}"; do
for str in "${!phrase[@]}"; do
echo "String: ${phrase[$str]}"
done
done
EXPLANATION

This script reads and prints each string character by character from the combined arrays. It starts by creating two arrays, stringPhrases_1 and stringPhrases_2, each containing distinct strings. It then combines these arrays into a new array named combinedStringPhrases. Using nested for loops, the script iterates through each element in the combined array, treating each element as a phrase. Within each phrase, it iterates through individual characters, printing each character with the label “String”.

List Multiple Arrays of Strings Together using for loop in bash scripting

Here, after merging 2 arrays each string element of the merged array is printed out.

8. Read the List of Strings Using a Pattern With “for” Loop

Pattern recognition and manipulation is a powerful technique to extract information from a string. The following example showcases this technique. It takes a hyphen-separated string as input and uses a “for loop” to break it into individual words.

#!/bin/bash

sentence="Linux-is a free-open-source-operating system"

for str in ${sentence//-/ }
do
echo "Word: $str"
done
EXPLANATION

This Bash script processes and prints each word in the hyphen-separated string after replacing hyphens with spaces. It starts with a string named “sentence” containing hyphen-separated words. Using a “for loop”, it replaces hyphens with spaces in the string and then iterates through each word. During each iteration, the script echoes the current word with the label “Word”.

Read the List of Strings Using a Pattern With “for” Loop

Here, every word in the string is echoed in a separate line.

Conclusion

Mastering the “for loop” in Bash elevates your scripting skills, giving you the precision to manipulate strings with ease. Whether parsing files, iterating through arrays, or employing custom delimiters, the “for loop” proves indispensable. Its simple yet adaptable nature makes it an essential tool for any Bash script. I hope you will embrace the power of the “for loop” and use it in bash scripting.

People Also Ask

How to iterate through a list in a shell script?

To iterate through a list in a shell script, you can use various methods, and the choice depends on the nature of your list. Here is a very simple example using a “for loop” with space-separated list elements:

#!/bin/bash

myList="item1 item2 item3 item4"
for item in $myList
do
echo "Current item: $item"
done

This script initializes a space-separated list called myList and iterates through its elements using a “for loop”. During each iteration, it prints the current item as “Current item: item1”, “Current item: item2”, and so forth for each element in the list.

Can you nest for loops in Bash?

Yes, you can nest for loops in Bash. Nesting means placing one or more loops inside another loop. This allows you to create more complex loop structures for iterating through multiple data sets. Here’s a simple example of nested for loops:

#!/bin/bash

for i in {1..3}; do
echo "Outer loop iteration $i"
for j in {A..C}; do
echo "    Inner loop iteration $j"
done
done

In this example, there’s an outer loop that iterates three times, and for each iteration of the outer loop, there’s an inner loop that iterates through the letters A to C. The output will show the iterations of both the outer and inner loops.

How do I create a list of strings in Bash?

To create a list of strings you can either use space-separated elements or an array. To create a list of strings using space-separated elements use listVariable="element1 element2 element3". And to create a list of strings using an array use arrayName=("element1" "element2" "element3").

How to print a list in a shell script?

To print a list in a shell script, you can use a simple “for loop”. Here’s an example script:

#!/bin/bash

# Define a list
myList=("apple" "banana" "orange" "cherry")

# Print each item in the list
for item in "${myList[@]}"; do
echo "$item"
done

This script initializes an array called myList with four elements and then uses a “for loop” to iterate through the list, printing each item on a new line.

How to iterate list items?

There are many ways to iterate list items. Here’s an example of iterating through a list in Bash using a “for loop”:

#!/bin/bash

# Define a list
myList="apple banana orange cherry"

# Use a for loop to iterate through the list
for item in $myList
do
echo "Current item: $item"
done

This Bash script initializes a space-separated list called myList, containing elements “apple”, “banana”, “orange”, and “cherry”. It then uses a “for loop” to iterate through each item in the list and echoes that item.

What is a Bash array?

A Bash array is a data structure that stores a collection of elements. It allows grouping multiple values under a single variable name. Arrays can hold various types of data. Elements are accessed using indices, and arrays offer flexibility for managing and manipulating data in Bash scripts. Here’s a simple example of a Bash array:

#!/bin/bash

# Define an array
myArray=("apple" "banana" "orange" "cherry")

# Access and print array elements
echo "First element: ${myArray[0]}"
echo "Second element: ${myArray[1]}"
echo "All elements: ${myArray[@]}"

This Bash script defines an array named myArray with four elements. It then accesses and prints the first and second elements individually, as well as all elements collectively, demonstrating basic array usage in Bash.

How do I list all files in the shell?

To list all files in the shell, you can use the ls command with different options. Type the ls command for a basic listing in the current directory. For detailed information, including file permissions and sizes, use ls -l command. To list all files including the hidden files use ls -a. To list the files recursively, use ls -R. You can also merge multiple options together.

Related Articles


<< Go Back to For Loop in BashLoops in Bash | Bash Scripting Tutorial

5/5 - (5 votes)
LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now
icon linux
Ridoy Chandra Shil

Hello everyone. I am Ridoy Chandra Shil, currently working as a Linux Content Developer Executive at SOFTEKO. I am a Biomedical Engineering graduate from Bangladesh University of Engineering and Technology. I am a science and tech enthusiast. In my free time, I read articles about new tech and watch documentaries on science-related topics. I am also a big fan of “The Big Bang Theory”. Read Full Bio

Leave a Comment