- Bash Array – How to Declare an Array of Strings in a Bash Script
- How to Declare an Array in Bash
- How to Access an Array in Bash
- How to Loop Through Array Elements
- How to Loop Through Array Indices
- Conclusion
- Bash “For” Loop To Iterate Through an Array
- Creating the Bash File
- Using the “for” Loop To Display the Contents of an Array
- Running the Script
- Using the “for” Loop To Write the Contents of an Array to a Text File
- Running the Script
- Using the “for” Loop To Compare a Given String With the Elements of the Array
- Running the Script
- Conclusion
- About the author
- Karim Buzdar
Bash Array – How to Declare an Array of Strings in a Bash Script
Veronica Stork
Bash scripts give you a convenient way to automate command line tasks.
With Bash, you can do many of the same things you would do in other scripting or programming languages. You can create and use variables, execute loops, use conditional logic, and store data in arrays.
While the functionality may be very familiar, the syntax of Bash can be tricky. In this article, you will learn how to declare arrays and then how to use them in your code.
How to Declare an Array in Bash
Declaring an array in Bash is easy, but pay attention to the syntax. If you are used to programming in other languages, the code might look familiar, but there are subtle differences that are easy to miss.
To declare your array, follow these steps:
- Give your array a name
- Follow that variable name with an equal sign. The equal sign should not have any spaces around it
- Enclose the array in parentheses (not brackets like in JavaScript)
- Type your strings using quotes, but with no commas between them
Your array declaration will look something like this:
myArray=("cat" "dog" "mouse" "frog")
How to Access an Array in Bash
There are a couple different ways to loop through your array. You can either loop through the elements themselves, or loop through the indices.
How to Loop Through Array Elements
To loop through the array elements, your code will need to look something like this:
for str in $; do echo $str done
To break that down: this is somewhat like using forEach in JavaScript. For each string (str) in the array (myArray), print that string.
The output of this loop looks like this:
Note: The @ symbol in the square brackets indicates that you are looping through all of the elements in the array. If you were to leave that out and just write for str in $ , only the first string in the array would be printed.
How to Loop Through Array Indices
Alternatively, you can loop through the indices of the array. This is like a for loop in JavaScript, and is useful for when you want to be able to access the index of each element.
To use this method, your code will need to look something like the following:
for i in $; do echo "element $i is $" done
The output will look like this:
element 0 is cat element 1 is dog element 2 is mouse element 3 is frog
Note: The exclamation mark at the beginning of the myArray variable indicates that you are accessing the indices of the array and not the elements themselves. This can be confusing if you are used to the exclamation mark indicating negation, so pay careful attention to that.
Another note: Bash does not typically require curly braces for variables, but it does for arrays. So you will notice that when you reference an array, you do so with the syntax $ , but when you reference a string or number, you simply use a dollar sign: $i .
Conclusion
Bash scripts are useful for creating automated command line behavior, and arrays are a great tool that you can use to store multiple pieces of data.
Declaring and using them is not hard, but it is different from other languages, so pay close attention to avoid making mistakes.
Veronica Stork
Veronica is a librarian by trade with a longtime computer programming habit that she is currently working on turning into a career. She enjoys reading, cats, and programming in React.
If you read this far, tweet to the author to show them you care. Tweet a thanks
Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started
freeCodeCamp is a donor-supported tax-exempt 501(c)(3) charity organization (United States Federal Tax Identification Number: 82-0779546)
Our mission: to help people learn to code for free. We accomplish this by creating thousands of videos, articles, and interactive coding lessons — all freely available to the public. We also have thousands of freeCodeCamp study groups around the world.
Donations to freeCodeCamp go toward our education initiatives, and help pay for servers, services, and staff.
Bash “For” Loop To Iterate Through an Array
A “for” loop is a fundamental part of almost every programming language. It helps write the code you want to be repeated in the desired number of times. For Linux-based systems, Bash also features dedicated syntax that enables its users to leverage loops for automating their day-to-day tasks through scripts.
Though you can use the “for” loop in a virtually infinite number of scenarios, this guide will look at three basic scenarios that you can plug into more extensive and complex scenarios to achieve bigger goals. We will explore three basic scenarios that employ the for loop for iterating through an array.
To demonstrate the working of the “For” loop, I will demonstrate the Bash scripts using Ubuntu 22.04.
Creating the Bash File
Before we explore the scenarios, let’s create our Bash file, which will contain our Bash script. Simply navigate to your desired directory in the terminal and create a file using the “nano” or “touch” command.
For this guide, I will create a “test.sh” file in my “Documents” directory.
This will open your Bash file using the nano text editor.
Here, you can start writing the code that you want in your script file. Let’s start by exploring the scenarios.
Using the “for” Loop To Display the Contents of an Array
With your Bash file opened up in the editor, we can start adding code to it. To specify that this is a Bash file, you need to indicate the following:
First, we need to define an array and assign five values to it. Let’s assign the names John, Jane, Jim, Jack, and Janis.
Now comes the fun part; we need to set up the for loop, which using the iterator “i” will iterate through the array’s contents and perform the display function. You can do it as such:
This line sets up the loop. With the “$” symbol, we are specifying that we are trying to access the value of the specific index of the array. The “@” symbol refers to the index of the array, which contains the value we are trying to access using the “i” iterator.
In Bash scripting, the syntax dictates that we specify our function within the “do” and “done” keywords. So, as we are trying to display the contents of the array, we will type it out as shown below:
This will go through all the contents of the array and display them one by one. Now, our script looks like this:
Press “Ctrl+O” to save the contents of this script file and “Ctrl+X” to exit from the nano editor.
Running the Script
With all the code in place, you might wonder how you can execute this code to see the output. In your terminal, type:
Here, you can see the names displayed as we have defined them.
Using the “for” Loop To Write the Contents of an Array to a Text File
This scenario works well in cases where we get the output of a specific scenario in an array, and we have to output the contents of the array for future reference or another calculation.
So, let’s take the code that we’ve written in the previous scenario and modify it. Instead of printing each entry in the array one by one, we need to write it out in a text file. Open up your script file using:
Now, as we have the array named “writers”, we will be writing them out to a file named “writers.txt” using the >> symbols. So your code should look like this:
Save and exit from the file to run the script.
Running the Script
Similar to the previous scenario, you can run the updated script using:
This time when you run the code, you will see that there will be no output in the terminal. This is because the code is outputting everything to the text file. A text file would have been created in the same directory.
Upon opening the file (you can just double-click on the file to open it), you will see that the names have been added to the file:
Using the “for” Loop To Compare a Given String With the Elements of the Array
We will use the same Bash script for this scenario and extend it further.
The main structure of our code will remain the same, and we will need to update the contents of the loop code. Using the same script, we will see if our provided name matches with any of the names in the array; if it does, we will greet them. For the other names of the array, it will just display them.
Let’s open up our file using “nano”:
Now, we’d want to update the code between the do and done keywords to the following:
This code will check at the time of execution if any of the names in the array match “Janis”, then display “Hi Janis”. Otherwise, just display the names. Your code should look like this:
In order to be able to run this code, you need to save the file and exit from the text editor.
Running the Script
When you are back in the terminal, you can use the same to execute your modified Bash script:
Conclusion
These three are very primitive examples of using the “for” loop in your Bash scripts. As you continue learning more about what these scripts can do, you’ll see that this loop comes in very handy and can be utilized in very complex codes. To better understand scripting and use it in your day-to-day operations, you need to understand these basic components of the code and what the syntax does.
If you run into any issues with any of these scenarios or want to learn more about loops or Bash scripting, feel free to engage us through the comments section, and we’ll be glad to help you out. Cheers.
About the author
Karim Buzdar
Karim Buzdar holds a degree in telecommunication engineering and holds several sysadmin certifications. As an IT engineer and technical author, he writes for various web sites. He blogs at LinuxWays.