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.
Table of Contents
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[*]}
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}
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]}
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[@]}
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[@]}
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[@]}
Print key and value pair
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[@]}
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
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[@]}
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
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[@]}
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]
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=()
Remove array
If you wish to remove the array, you can use the array name without any keys.
$ unset STAR_PLAYERS
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.
Related read:
- Bash Scripting – While And Until Loop Explained With Examples
- Bash Scripting – For Loop Explained With Examples
- Bash Scripting – Functions Explained With Examples
- Bash Scripting – Variables Explained With Examples
- Bash Redirection Explained With Examples
- Bash Echo Command Explained With Examples In Linux
- Bash Heredoc Tutorial For Beginners
2 comments
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
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.