FUNDAMENTALS A Complete Guide for Beginners
An Associative array in Bash is a robust data structure providing flexibility in data management. It can assign values to specific keys, iterate over them, or perform various operations like adding or removing elements.
Let’s walk through the essential concepts along with Bash script examples to work with the Associative array in Bash.
What is an Associative Array in Bash?
An associative array in Bash is an array data structure that operates using key-value pairs. Every key (also called string index) is unique and associated with values to work with. Bash Associative array holds keys and values of string data type.
Associative arrays in Bash are also commonly known as “Bash hash array”, “Bash map array”, and “Bash key-value array”.
NOTE: To learn more about arrays in Bash, read the article, “Bash Array”.
Declare an Associative Array in Bash
Unlike an index array, it’s impossible to declare, create, or even initialize an associative array without the declare command but with the -A
option. The -A option is a must to notify the system about the creation of a Bash associative array.
To declare an associative array, use the syntax: declare -A
. Here’s an example:
#!/bin/bash
#declare an associative array and assign values
declare -A my_associative
my_associative["eat"]="rice"
my_associative["take"]="tea"
my_associative["drink"]="juice"
#printing message for verification
echo "the array is declared using declare -A"
In the above code, the declare -A
command creates an associative array named my_associative and initializes 3 key-value pairs afterward. The echo command prints a message to verify the successful running of code.
declare -A
command
Access Associative Arrays in Bash
To access a Bash associative array usually means to view all its values associated with every unique string index (keys). The length expressions ${assoc_array[@]} or ${assoc_array[*]} with the echo command prints all the values of the given array.
Here’s how to print the values of a Bash associative array using the syntax echo ${assoc_array[@]}
:
#!/bin/bash
#declare an associative array and assign values
declare -A my_associative
my_associative["eat"]="rice"
my_associative["take"]="tea"
my_associative["drink"]="juice"
#printing the array
echo ${my_associative[@]}
In the above Bash script, the declare -A
command creates an associative array named my_associative and later initializes with 3 key-value pairs. Finally, the command echo ${my_associative[@]}
prints the array values on the screen.
echo ${my_associative[@]}
command expands the array and prints the values on the terminal.
Print Specific Values of an Associative Array
To print the values of only the specific keys of an associative array, use this simple syntax: echo ${assoc_array[key]=value}
Look at the following example:
#!/bin/bash
#declare an associative array
declare -A assoc_array
#value insertion to the array
assoc_array["fruit"]="apple"
assoc_array["vegetable"]="carrot"
assoc_array["drink"]="water"
#print only the 2nd and 3rd values
echo ${assoc_array["vegetable"]}
echo ${assoc_array["drink"]}
In this script, the echo ${assoc_array["vegetable"]}
and echo ${assoc_array["drink"]}
expressions access the keys (vegetable drink) of the assoc_array and print the values (carrot water) to the screen.
Printing All the Keys
Apart from printing the values, the length expressions ${assoc_array[@]} or ${assoc_array[*]} print only the keys by prefixing them with ‘!’. The complete syntax is: echo ${!assoc_array[@]}
or echo ${!assoc_array[*]}
To print the keys of an associative array using, echo ${!assoc_array[@]}
see the example below:
#!/bin/bash
#declare an associative array and assign values
declare -A my_associative
my_associative["eat"]="rice"
my_associative["take"]="tea"
my_associative["drink"]="juice"
#printing the array keys
echo "keys: ${!my_associative[@]}"
In the Bash script above, echo "keys: ${!my_associative[@]}"
prints only the keys of the array named my_associative. Here, the length expression ${!my_associative[@]} expands just the keys and returns them on the screen with the echo command.
echo "keys: ${!my_associative[@]}"
command prints only the keys (take drink eat) associated with the 3 values (tea juice rice).
Print Keys and Values
If you are willing to print both the keys and values of a Bash associative array, use the for loop and avail the syntax: for key in "${!assoc_array[@]}"
which iterates through the keys to locate the elements and the echo command prints both the key-value pair of an associative array in Bash.
Here’s an example of printing the key-value pairs of an associative array:
#!/bin/bash
#declare an associative array
declare -A assoc_array
#value insertion to the array
assoc_array["fruit"]="apple"
assoc_array["vegetable"]="carrot"
assoc_array["drink"]="water"
#for loop to print the key value pairs
for elem in "${!assoc_array[@]}"
do
echo "key : ${elem}" -- "value: ${assoc_array[${elem}]}"
done
In the aforementioned script, the loop for elem in "${!assoc_array[@]}"
iterates through the keys, and the expression inside the loop echo "key: ${elem}" -- "value: ${assoc_array[${elem}]}"
prints the keys and values one by one with new lines.
Find the Length of an Associative Array
The length refers to the total number of elements in an associative array. The Length expression syntax echo ${#array[@]}
prints the array length where ‘#’ corresponds to the value of the array length.
Below is an example to print the length of an associative array in Bash:
#!/bin/bash
#declare an associative array and assign values
declare -A my_associative
my_associative["eat"]="rice"
my_associative["take"]="tea"
my_associative["drink"]="juice"
#print elements
echo "values: ${my_associative[*]}"
#printing the array length
echo "length: ${#my_associative[@]}"
This Bash script expands all the elements of the array my_associative and the “#” sign stores the number of those elements. Finally, the echo command prints the value of the array length. In the previous line, the echo command also prints the elements to verify the length.
echo "length: ${#my_associative[@]}"
Append New Values to an Associative Array
The term “append values” refers to adding new elements to an associative array by providing a key-value pair. To append elements to an associative array, use the syntax assoc_array+=(["key"]="value")
.
Here’s an example:
#!/bin/bash
#declare an associative array and assign values
declare -A players
players["football"]="kaka"
players["cricket"]="ganguly"
players["basket"]="jordan"
#print before append
echo "before append: ${players[@]}"
#append to array
players+=(["tennis"]="federer")
#print after append
echo "after append: ${players[@]}"
This script uses the syntax players+=(["tennis"]="federer")
to append a new element federer to the players array with 3 elements. The final echo command prints the array with 4 elements (kaka ganguly jordan federer).
players+=(["tennis"]="federer")
expression adds a new key-value pair ([“tennis”]=”federer”) to the extant array players.
Append Values Using the “=” Operator
Alternatively, you can append elements to an associative array with the “=” operator using the syntax assoc_array[“key”]=”value”.
I’ll use the same previous example array to add a new element in the below example:
#!/bin/bash
#declare an associative array and assign values
declare -A players
players["football"]="kaka"
players["cricket"]="ganguly"
players["basket"]="jordan"
#print before append
echo "before append: ${players[@]}"
#append to array
players["metallica"]="Hetfield"
#print after append
echo "after append: ${players[@]}"
Terminal output to add new element Hetfield to the associative array players using
players["metallica"]="Hetfield"
NOTE: If you use the same key already present in the array to append, the new value simply overrides the former one.
Delete Elements of an Associative Array
The unset command deletes any specified element from the array by removing the key-value pair. The syntax unset assoc_array["KEY"]
helps to clear the specific element associated with the KEY.
Look at the example below to Delete a Bash associative array element:
#!/bin/bash
#declare an associative array
declare -A assoc_array
#value insertion to the array
assoc_array["fruit"]="apple"
assoc_array["vegetable"]="carrot"
assoc_array["drink"]="water"
#print array
echo "${assoc_array[@]}"
#remove array element
unset assoc_array["drink"]
#print array after removal
echo " after removing: ${assoc_array[@]}"
In the script, unset assoc_array["drink"]
removes the key-value pair (drink: water) and the echo command prints the remaining 2 values to verify the deletion.
unset assoc_array[“drink”]
command removes the key drink and its corresponding value water from the array and echo " after removing: ${assoc_array[@]}"
print the 2 values that are still in existence (apple carrot).
Empty an Associative Array
To make an associative array empty by removing all of its key-value pairs, simply recreate the array using the syntax: declare -A assoc_array_name=()
:
#!/bin/bash
#declare an associative array
declare -A food
#value insertion to the array
food["fruit"]="apple"
food["vegetable"]="carrot"
food["drink"]="water"
#print the array
echo "all the elements: ${food[@]}"
#recreate the array and remove all elements
declare -A food=()
#print again
echo "the array after recreating: ${food[@]}"
Here, the declare -A food=()
recreates the already extant array called food with 3 elements (apple carrot water). In turn, it also removes all the items and only the empty array remains which is evident in the last line where the echo command tries to print the elements and gets nothing.
declare -A food=()
Remove a Bash Associative Array
To remove an associative array in Bash, use the unset command with the syntax unset <assoc_array>
. Here’s how:
#!/bin/bash
#declare an associative array
declare -A food
#value insertion to the array
food["fruit"]="apple"
food["vegetable"]="carrot"
food["drink"]="water"
#print the array
echo "all the elements: ${food[@]}"
#remove all elements using syntax unset <array_name>
unset food
#print again to verify that the items got removed
echo "array without elements: ${food[@]}"
In the above script, unset food
deletes the associative array named food. Printing the array after running the unset food displays no elements on the screen that verify the element removal.
echo ${food[@]}
. This empty result is the exemplar that the array food has no items remaining.
Create a Read-Only Associative Array
In a read-only state, it’s not possible to modify the associative array once it’s initialized. To declare an associative array in Bash in Read-only mode, use the declare command with the -r flag.
To declare a read-only associative array using the syntax declare -r -A <array_name>
, follow the example below:
#!/bin/bash
#declare an associative array with a -r flag
declare -r -A food=(
food["fruit"]="apple"
food["vegetable"]="carrot"
food["drink"]="water"
)
#delete element
unset food["fruit"]
Here, the command declare -r -A food=(food[“fruit”]=”apple” food[“vegetable”]=”carrot” food[“drink”]=”water”) declares an associative array food with 3 elements but with the read-only mode using the -r flag. That’s why the unset food["fruit"]
command is not able to delete the value apple or its key fruit.
declare -r -A
command makes the array food read-only which, in turn, makes any sort of modification to the food array impossible.
Check if an Element Exists in the Associative Array
There are many ways to check if an element exists in an associative array. However, the simplest way is to use the if conditional statement with the -n flag. The complete syntax if [[ -n “$assoc_array[KEY]}” ]] checks whether the string returned from “$assoc_array[KEY]}” is non-zero. It expands the given KEY and the -n checks for the value.
To check if an element exists in an associative array using the conditional if [[ -n "$assoc_array[KEY]}" ]]
, see the below example:
#!/bin/bash
#declare an associative array
declare -A assoc_array
#value insertion to the array
assoc_array["fruit"]="apple"
assoc_array["vegetable"]="carrot"
assoc_array["drink"]="water"
#print the array values
echo "values: ${assoc_array[@]}"
echo
#print keys
echo "keys:${!assoc_array[@]}"
echo
echo "check for KEY fruit"
#check if element is extant in the array
if [[ -n "${assoc_array[fruit]}" ]]
then
echo "Element is present"
else
echo "Element not present"
fi
echo
echo "checking for key canada"
if [[ -n "${assoc_array[canada]}" ]]
then
echo "Element is present"
else
echo "Element not present"
fi
In the above code, if [[ -n "${assoc_array[fruit]}" ]]
condition checks if it returns any non-empty string (value apple corresponding to the key fruit). Since it finds apple, it prints “Element is present”. On the other hand, it prints “Element not present” as there’s no key named canada in the assoc_array.
if [[ -n "${assoc_array[fruit]}" ]]
.
Conclusion
In closing, I Hope the discussion along with practical examples guides you through the ins and outs of the associative array in Bash. It is a versatile tool for storing and manipulating collections of items, offering flexibility in managing data within scripts. if you face any difficulty, feel free to share in the comment section. Happy scripting!
Frequently Asked Questions
Is there a way to create key-value pairs in a Bash script?
Yes, in Bash version 4, associative arrays were introduced that work based on key-value pairs. It’s also known as “key-value dictionaries”. For example:
declare -A arr
arr["key1"]=val1
arr+=( ["key2"]=val2 ["key3"]=val3 )
The above shows an associative array named arr which has 3 key-value pairs.
What’s the difference between an indexed array and an associative array in Bash?
Index array uses numerical indices (0 1 2) to store and retrieve elements. Contrarily, the Bash associative arrays allow the customization of indices by employing user-defined keys with unique values providing a more non-sequential approach to data handling.
Is it possible to print an associative array in reverse?
No, the associative arrays in Bash do not have any sequential order of storing and handling data. This is why it is not possible to print the array elements in the reverse order which is seamlessly available for indexed arrays.
How do I declare an associative array in Bash?
You have to use the declare command with -A flag to declare a Bash associative array. Without the -A
flag, Bash treats the array as a general indexed array. For instance, to declare an associative array named students, use the syntax: declare -A students
.
Can I get the length of an associative array in Bash?
Yes. To get the length of a Bash associative array, use the length expression syntax ${#example_array[@]} with the echo command. This will return the total element count to the screen. For instance, after declaring the assoc_array with the command declare -A assoc_array
with no elements, using the syntax echo ${#assoc_array[@]}
will print 0 as its length since the array is empty.
Do “Bash associative array”, “ Bash hash array”, “Bash map array” and “Bash key-value array” refer to the same meaning?
Absolutely. All the terms refer to the associative array that pairs some user-defined keys with corresponding values.
How can I modify elements in a Bash associative array?
To modify any element in a Bash associative array, use the assignment syntax: assoc_array[“old_key”]=”new_value”. This will replace the old value with the newly defined value associated with old_key.
In addition, to add a new element in the array, use assoc_array[“new_key”]=”new_value”.
For example, to modify the 2nd element of myArray=([key1]="value1" [key2]="value2")
:
myArray[key2]="new_value"
How do I print a Bash associative array?
You can use the command echo ${assoc_array[@]} or echo ${assoc_array[*]} to print the values of an associative array in Bash.
To print the key-value pair, you can use the Bash for loop like the following:
#for loop to print the key-value pairs:
for elem in "${!assoc_array[@]}"
do
echo "key : ${elem}" -- "value: ${assoc_array[${elem}]}"
done
What is an associative array in Bash?
An associative array in Bash is a data structure just like dictionaries in Python storing key-value pairs. Every key must be unique containing a value. Associative arrays provide ways to index and access value depending on the corresponding key which is also called string index.
How to print only the keys of an associative array in Bash?
To print only the keys of an associative array in Bash, use the syntax echo ${!example_array[@]}. For example, if you have an associative array named assoc_array=([“key1″]=”value1”, [“key2″]=”value2”, [“key3″]=”value3”) and you use the syntax echo ${!assoc_array[@]}
, it will print the 3 keys namely key1 key2 key3 in any random order on the terminal.
How do I clear an associative array in Bash?
You can use the unset command followed by the array name to clear the Basha associative array. For example, if food is an associative array with 2 elements in the form declare -A food=(["fruit"]="apple" ["vegetable"]="carrot" ["drink"]="water")
, using the syntax unset food
will clear the entire array by removing all the key-value pairs.
Related Articles
- Declare Array in Bash [Create, Initialize]
- How to Read into Bash Array [3 Methods]
- Index Array in Bash [Explained]
- Bash Array of Arrays [Explained]
- Elements of Bash Array
<< Go Back to Bash Array | Bash Scripting Tutorial