Home Bash scripting Bash Scripting – Associative Array Explained With Examples

Bash Scripting – Associative Array Explained With Examples

By Karthick
Published: Updated: 40.9K views

This is the second article as part of bash arrays. In the previous article, we have discussed how to work with Indexed arrays in Bash. In this guide, we will discuss about Bash Associative Array in detail with examples in Linux.

Associative arrays work based on key-value pairs. In some languages, it is also called dictionaries or hash maps. The main difference between Indexed and Associative arrays is, Indexed arrays works based on index value, and each element in the array is mapped to a particular index position of the array. An associative array uses a "key" to map the value instead of index positions.

Let’s dive in and see how to use associative array in bash.

Initialize associative array

Unlike an Indexed array, you cannot initialize an associative array without using declare command.

Use the declare command with -A flag.

$ declare -A STAR_PLAYERS=()

Now an empty array named "STAR_PLAYERS" is created. If you wish you can also add elements to the array directly during the initialization.

$ declare -A STAR_PLAYERS=( [Argentina]="Messi" [Brazil]="Neymar" [England]="Kane" )

In the above code, the keys are within square brackets and values should be followed by equal to sign without any spaces. There is no need to use a comma or semicolons as a separator between elements.

For better readability, you can write the array elements over multiple lines.

$ declare -A STAR_PLAYERS=(
 [Argentina]="Messi"
 [Brazil]="Neymar"
 [England]="Rooney"
)

View array elements

You have to use the echo or printf command in bash to print the contents of the array. Similar to how we used the special variable * and @ to print the Indexed array, the same should be used to print associative arrays too.

$ echo ${STAR_PLAYERS[@]}
$ echo ${STAR_PLAYERS[*]}
Print Associative array
Print Associative array

There is a significant difference between * and @ and to know the difference between * and @ and how it works with array, refer the section "Loop over array elements" in our Bash For Loop guide.

If you try to print the array elements without using * or @, the output will be empty.

$ echo ${STAR_PLAYERS}
Print array without * or @
Print array without * or @

Also if you take a look at the above output, only the values are printed and not the keys. The values you print will not be ordered. You can grab the value of a particular element using its key.

$ echo ${STAR_PLAYERS[Brazil]}
Print particular element
Print particular element

Add new elements to the array

Adding a new element to the array is simple. All you have to do is create a new key-value pair like as shown below.

$ STAR_PLAYERS[Belgium]="Hazard"
$ echo ${STAR_PLAYERS[@]}
Add new element to the array
Add new element to the array

If you try to use the same key that is already present in the array, the value will be overridden with the new one.

$ STAR_PLAYERS[England]="Sterling"
$ echo ${STAR_PLAYERS[@]}
Override the value
Override the value

Append new elements to the array

You can also append elements to an array using the following syntax.

$ STAR_PLAYERS+=([Spain]="Ramos")
$ echo ${STAR_PLAYERS[@]}
Append value to array
Append value to array

From previous examples, you might have understood that only the values are printed. You can get the list of keys alone by prefixing the "!" symbol with the array.

$ echo ${!STAR_PLAYERS[@]}
Print keys alone
Print keys alone

If you wish to print both key and value at the same time, you can use the for loop.

for elem in "${!STAR_PLAYERS[@]}"
do
 echo "key : ${elem}" -- "value: ${STAR_PLAYERS[${elem}]}"
done
Print keys and values
Print keys and values

Length of associative array

You can get the length of the associative array i.e total number of elements present in the array by prefixing "#" symbol with the array. This is common for Indexed arrays too.

$ echo ${#STAR_PLAYERS[@]}
Length of an array
Length of an array

Check if element is present in the array

Sometimes before doing any processing with the particular element, you may wish to check if the element is already present in the array. There are many ways to do this but below is the simplest way.

I am using the conditional statement with the -n flag which will check if the length of the string returned from ${STAR_PLAYERS[Argentina]} is non-zero. It expands the given key and the value is actually checked against the -n flag.

if [[ -n "${STAR_PLAYERS[Argentina]}" ]] 
then
  echo "Element is present"
else
  echo "Element not present"
fi
Check element presence in the array
Check element presence in the array

Read only associative array

You can make an associative array read-only. In a read-only state, once the array is initialized you cannot add new elements to the array or modify any values within the array. Along with the declare command you have to use the -r flag.

$ declare -r -A STAR_PLAYERS=(
 [Argentina]="Messi"
 [Brazil]="Neymar"
 [England]="Rooney"
)
$ STAR_PLAYERS[Spain]="Ramos"
$ STAR_PLAYERS[England]="Sterling"
$ echo ${STAR_PLAYERS[@]}
Read-only associative array
Read-only associative array

Remove elements

If you wish to remove any particular element from the array, you can use the unset command with the element key name. For example, if I wish to remove the element (Spain="Ramos"), then the syntax should be as follows.

$ unset STAR_PLAYERS[Spain]
Remove particular element
Remove particular element

Empty an array

You can also remove all the elements from the array and make it empty by reinitializing the array like as shown below.

$ echo ${STAR_PLAYERS[@]}
$ declare -A STAR_PLAYERS=()
Make array empty
Make array empty

Remove array

If you wish to remove the array, you can use the array name without any keys.

$ unset STAR_PLAYERS
Remove array
Remove array

Conclusion

In this article, we have seen what is associative arrays in bash and some of its functionalities. The drawback with bash is you either have to write some logic manually or use external tools to achieve the desired result. For example, when I have to convert associative array to json objects, then I have to use jq tool which is not built-in to bash. This is where you should try using Python which offers easy-to-use methods when you have to work with arrays and other data structures.

You May Also Like

2 comments

Alevanpa September 4, 2022 - 11:02 pm

AlevasiPad:: declare -A STAR_PLAYERS=(
-ash: syntax error: unexpected: “(“
AlevasiPad:

I’m trying to use the command line to create the array exactly as you show it on you4 wiki, but I’m getting the same error, unexpected “(“, each time.

If I put the same code in a BASH script, it works fine.

Have you any idea what is wrong by running the code from the command line?
I’m using “Alpine Linux” version: 5.1.16(1)-release (2020), on a 4th gen iPad Air. iPad software version: 15.6.1

Reply
sk September 5, 2022 - 11:08 am

I haven’t checked the code in Alpine Linux yet. You get this error because Alpine Linux uses ash shell by default. You can either try to get help from Alpine Linux community or install Bash shell in Alpine Linux and try again. Good luck.

Reply

Leave a Comment

* By using this form you agree with the storage and handling of your data by this website.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

This website uses cookies to improve your experience. By using this site, we will assume that you're OK with it. Accept Read More