Bash: How to iterate through a list of strings
Have you ever needed to perform the same operation on multiple strings in a BASH script? In this article, we'll explore how to achieve this by iterating over a list or array of strings defined in a variable.
The sample script
Let's start with a sample BASH script that demonstrates this concept. You can directly execute this script in a Bash shell or include it in a script file.
declare -a entries=(
"First"
"Second"
"Third"
"The fourth"
)
for entry in "${entries[@]}"; do
echo "$entry entry"
done
If we execute the script we'll get the following output:
First entry
Second entry
Third entry
The fourth entry
This basic script illustrates the concept, but you can leverage it for more complex operations. For example, executing commands for each entry or using the entries as input parameters for other expressions.
Understanding the script
Let's now analyze each part of the script to understand how it works.
Declaring an array variable
The first line of the script declares an array variable named entries
by leveraging the
declare
BASH builtin.
The declare
syntax for this case is as follows:
declare -a name=(value1 value2 ... valueN)
Declaring arrays explicitly is a good practice in BASH scripting.
Iterating over the array
To iterate over the array we use a looping construct like this:
for entry in "${entries[@]}"; do
Here, we expand the array variable entries
using "${entries[@]}"
.
This preserves the individual elements, including spaces within them.
Without the double quotes, elements like "The fourth" would be treated as separate words.
This would be the output in case we missed enclosing the variable in double quotes:
First entry
Second entry
Third entry
The entry
fourth entry
By following these practices, you can effectively iterate through a list of strings in your BASH scripts. Now, you have the knowledge to apply this technique to various scenarios in your scripting endeavors.
Happy scripting!