Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to Use Bash Arrays
#1

    How to Use Bash Arrays

What Is a Bash Array?



    A bash array is a data structure designed to store information in an indexed way. In other words, a bash array is a large group of variables. Unlike typical arrays used in other programming languages, bash arrays can store different types of elements. For example, you can use a bash array to store both strings and numbers.


There are two types of bash arrays:
       
  • Indexed – the array is referred via integers or numbers.
  •    
  • Associative – the array is referred via strings or a set of characters and words.


    Remember that bash does not support multidimensional arrays, so it’s not possible to add an array within an array.


How to Declare Array in Bash



    There are a few ways to declare indexed and associative arrays in bash. It’s worth noting that the bash array size does not need to be declared beforehand because bash arrays have no upper limit on the number of elements they can store.


Indexed Array



    We will start with a simple bash indexed array. For example, we’ll use it to create a list of different means of transportation.


declare -a IndexedArray
IndexedArray[0]=car
IndexedArray[1]=plane
IndexedArray[2]=bike


    The same can be achieved without the declare builtin:


IndexedArray[0]=car
IndexedArray[1]=plane
IndexedArray[2]=bike


    Or, make it even simpler by going with:


IndexedArray=(car plane bike)


    Remember that indexing starts at 0, so the above example will assign the car element of the array to the 0 index.



    However, there is an option to set an array with indices:


IndexedArray=([0]=’car’ [1]=’plane’ [2]=’bike’)


    An interesting feature of bash arrays is that following index numbers in order is not necessary. For example, you can declare only the first and third elements while leaving the second element of an array empty:


IndexedArray[0]=car
IndexedArray[2]=bike


Associative Array



    While indexed arrays don’t require the declare builtin, it won’t be possible to create an associative bash array without declaring it first:


declare -A AssociativeArray


    Next, add the values. Keep in mind that the key must be a string:


AssociativeArray[color]=blue
AssociativeArray[type]=car
AssociativeArray[topspeed]=200


    An alternative way would be:


declare -A AssociativeArray=( [color]=blue [type]=car [topspeed]=200 )


How to Add a Variable to a Bash Array



    Easily add bash variables using the += operator. For example, the process for an indexed array would look like this:


IndexedArray=(car plane bike)
IndexedArray+=(motorcycle)


    The indexed array has a new element now. Remember that this method appends to the end of an array. Therefore, the motorcycle element will be added as the last element.



    For associative arrays, the process is very similar. Except, you need to specify the keys along with all the elements:


declare -A AssociativeArray
AssociativeArray[color]=blue
AssociativeArray+=([tires]=alloy [engine]=gasoline)


How to Reference and Print an Array Element



    Users can reference bash array values using the element index or key. To do this, create an indexed array:


IndexedArray=(car plane bike)


    To reference the first array variable, use the following syntax:


${IndexedArray[0]}


    Combine it with echo, and you will get the following:


echo ${IndexedArray[0]}


    The output will show you the first element. In this case, it’s car. The same logic applies when referencing and printing an associative array:


declare -A AssociativeArray=( [color]=blue [type]=car [topspeed]=200 )
echo ${AssociativeArray[type]}


    The output will be car as well.


    To print the whole array, use @ as an index. The full script looks like this:

Indexed Array Example

    You can also print the keys of an array instead. To do this, add an exclamation mark before the array name:

Associative Array Example

How to Remove Bash Array Elements



    Deleting array elements is similar to referencing them. Use an index or a key combined with the unset builtin to delete an array element.


    Here’s an example of deleting a single element from an indexed array:

Delete Indexed Array Element

    A similar logic applies to associative arrays:

Delete Associative Array Element

    To delete an entire array, specify unset with the array name as shown here:

Delete Entire Array

    Nothing is shown after trying to print the array elements because the unset builtin deleted them.


How to Loop Through an Array



    Creating bash loops is a fundamental aspect of learning bash scripting basics. You can use loops with arrays as well. For example, the most common use case is to iterate over each array item:

Loop Through Array

    You can also combine keys with the array elements and print them all together like this:

Loop Through Associative Array

How to Pass an Array to a Function



    Functions save a considerable amount of time when scripting. Instead of writing the same code repeatedly, you can call out an already written function. We will combine the codeviously mentioned iteration loop and make a function out of it:


function Iteration
{
m=${#IndexedArray[@]}
for (( i=0; i do
echo ${IndexedArray[$i]}
done
}
IndexedArray=(car bike plane)
Iteration ${IndexedArray[@]}


    Running it on the command line will get you the following result:

Pass Array to Function


   

   

Reply


Messages In This Thread
How to Use Bash Arrays - by aaron - 07-22-2023, 05:12 AM

Forum Jump:


Users browsing this thread: 1 Guest(s)