Bash Scripting
  • scripting list
  • How to Make Bash Script Executable Using Chmod
  • Shell Script to Check Linux Server Health
  • How to Concatenate String Variables in Bash [Join Strings]
  • How to Do Bash Variable Substitution (Parameter Substitution)
  • Bash Parameter Expansion with Cheat Sheet
  • Bash getopts with Examples
  • How to Pass all Arguments in Bash Scripting
  • Bash Function Return Value
  • Bash Loop Through Lines in a File
  • Bash readarray with Examples
  • Bash let with Examples
  • Bash expr with Examples
  • Bash read password
  • Bash for Loop Range Variable
  • Bash Arrays Explained
  • Ways to Find Bash Array Length
  • Bash Split String by Delimiter
  • Bash if Options
  • Bash If Statements for String Comparison
  • Debugging Techniques for Bash Scripts
  • Determining if a Bash String is Empty
  • Bash if Statement with Multiple Conditions
  • Meaning of Shebang in Bash Scripts
  • How to Comment Code in Bash Script
  • How to Read CSV File in Bash
  • Bash Scripting: How to Check if File Exists
  • Bash If Else Statements: Examples and Syntax
  • Bash Scripting: How to Check if Directory Exists
  • Bash eval Command with Examples
  • How to Use Sleep Command in Bash Scripting
  • Bash Associative Arrays with Examples
  • Bash Script for Counting Lines in a File
  • How to Use While Loop in Bash for Efficient Scripting
  • Bash basename Command with Examples
  • How to Create Multiline Strings in Bash
  • How to Use Bash if With && Operator
  • 50 Bash Script Examples to Kickstart Your Learning
  • Case statement in Bash Shell Scripting
  • Trimming White Space in Bash
  • How to Extract Filename from Absolute Path in Bash
  • How to Get Directory Path in Bash
  • Extract Extension from File Path in Bash
  • Extract Filename without Extension from Full Path in Bash
  • Bash for Each File in a Directory
  • Bash for Loop with Array
  • Bash Continue – Using with for Loop
  • Bash Backticks vs Dollar Parentheses $()
  • How to Assign Variable in Bash
  • How to Assign Variable in Bash
  • Bash Division Explained
  • Bash Modulo (Division Remainder)
  • Bash While Read Line by Line
  • Bash shift Command
  • Bash Looping Through Array of Strings
  • Bash read Command with Examples
  • Bash Check Empty Array
  • Using Bash For Loops to Iterate Over a List of Strings
  • Bash Break – Using with For Loop
  • How to Use seq With for Loop in Bash
  • How to Use $@ in Bash Scripting
  • Get the Current Script Directory in Bash
Powered by GitBook
On this page
  • What are associative arrays?
  • Creating associative arrays
  • Accessing the Associative Array
  • Delete operations
  • Example: A two-dimensional associative array
  • Conclusion

Bash Associative Arrays with Examples

PreviousHow to Use Sleep Command in Bash ScriptingNextBash Script for Counting Lines in a File

Last updated 1 year ago

A Bash variable only holds a single value. To hold multiple values at the same time, we bring arrays into the picture. An array is a mere collection of items holding some information. Bash arrays are unique as they can save different types of elements. If the size of the array is unknown, associative arrays are preferred. Since they associate the value and the index together, they are called associative arrays. In this tutorial, we will learn about these arrays, which store entries like a map.

What are associative arrays?

The bash arrays can be broadly categorized into numerically indexed arrays and associative arrays. In indexed arrays, elements are stored and assigned an integer number starting from 0. Associative arrays behave like a map and the values are made accessible using a key.

Basic Syntax:

declare -A array=(["key"]="value" ["key"]="value" ["key"]="value")

Here declares an associative array named "array" with three key-value pairs.

Creating associative arrays

Declaring

The associative arrays have to be declared with the keyword 'declare' with the -A option. This option is a must to ensure the array is associative. Without the -A option, an indexed array will get declared.

Example:

declare -A array

We have used this example to create an empty array named "array". It will not have any entry or key-value pair. Its size will be zero as it has only been declared. It is a fresh array.

Initializing

We can declare and add elements to the array during the creation itself.

Example:

declare -A array=(["Paris"]="France" ["Vienna"]="Austria" ["Oslo"]="Norway")

The keyword, mentioned inside the square brackets, is referred to as the key. Each key has a corresponding value. In this example, we have declared an associative array with three key-value pairs: Paris-France, Vienna-Austria and Olso-Norway.

If we have a populated array, we can see how it has been initialized using the -p flag. When it will act on the above array, it will give the entire command of how we initialized it.

Example:

declare -p array

Adding elements to an existing array

We can keep on adding more elements to the associative array:

Example:

declare -A array=(["Paris"]="France" ["Vienna"]="Austria" ["Oslo"]="Norway")
array["Warsaw"]="Poland"
array["Helsinki"]="Finland"

We have initialized an associative array with three entries. Next, we are adding another entry to the map. After adding the key value pair of Warsaw-Poland, the entries in the array will be four. Similarly, we have added another Helsinki-Finland key-pair value. The array now holds five elements.

Appending elements

Given an associative array, we can append one or more key value pairs using the += operator.

Syntax:

array+=([key1]=value1 [key2]=value2 [keyN]=valueN)

Example:

#!/bin/bashdeclare -A arrarr[Paris]=Francearr[Vienna]=Austriaecho -n "Current array "echo ${arr[*]}arr+=([Olso]=Norway [Warsaw]=Poland)echo -n "After appending 2 more elements it becomes "echo ${arr[*]}

We are declaring an associative array. Then we add the entries Paris-France and Vienna-Austria as two key-value pairs. When we print the array, we get to see its contents. Then using the += operator, we append two more elements to the array. Finally, when we print the array after this, we get to see that now the array holds 4 entries.

Creating on the fly

We cannot create an associative array on the fly in Bash. We have to use the declare built-in command with "-A" explicitly. We can rely on the += operator which makes it possible to append one or more key-value pairs to the associative Bash array.

Example:

#!/bin/bashdeclare -A arrarr[Paris]=Francearr[Vienna]=Austriaarr+=([Olso]=Norway [Warsaw]=Poland)echo ${arr[*]}

Accessing the Associative Array

Printing the array entries of the map is pretty straight forward. To refer to all the members of the array, we use the @ symbol. The use of the ∗ symbol as an index also gives the same output. The array, present inside the ${} construct, gets subjected to the parameter expansion.

Keys

We can get the list of keys alone by prefixing the "!" symbol with the array.

Example:

declare -A arr=(["Paris"]="France" ["Vienna"]="Austria" ["Oslo"]="Norway")
echo ${!arr[@]}

Values

We can get the list the values of an associative array like we would do for any Bash array using the "@" symbol

Example:

declare -A arr=(["Paris"]="France" ["Vienna"]="Austria" ["Oslo"]="Norway")
echo ${arr[@]}
echo ${arr["Olso"]}

In this example, we are getting the entire list of values by placing the "@" symbol between the two square brackets. If we place the key there, we will get the corresponding value present in the map. In our case, arr["Olso"] will echo Norway on the screen.

Key-Value pairs

We can iterate over an associative array using loops to fetch the key-value pair.

Example:

#!/bin/bashdeclare -A arr=(["Paris"]="France" ["Vienna"]="Austria" ["Oslo"]="Norway")for i in ${!arr[@]} do echo $i:${arr[$i]} #key:value done

There is no particular order in the output. It differs from the order of initialization.

In index based arrays, we used ${#arr[@]} to retrieve the number of elements in the array. Index values are actually the keys in the map. Associative arrays return keys rather than indexes. Therefore, this incremental looping is not apt for maps.

Delete operations

In Bash, we can either delete the entire array in one go or remove a particular element. We can also put this inside a loop to delete elements one by one or as per the situation.

Remove elements from the array

To remove an element from the array, we use the unset command. Unsetting a variable instructs Bash to discard the variable from the list of variables for tracking. We cannot access the stored value in the variable once it is unset. To unset, we need to provide the key within the square brackets.

Syntax:

unset arrayname[key]

Example:

unset array[Vienna]

Delete the entire array

We used the unset command to remove an element from the array. The same way we can destroy the complete array.

Example

unset arr

Clear the entire array

We might also want to clear the contents of the complete array. This will empty the array. To achieve this we just need to re-declare the array again. All the previously available information in the array gets cleared.

Example:

declare -A arr=()

Example: A two-dimensional associative array

We have understood how associative arrays work. Now, let us look at a real-world problem. In this, we will implement 2D arrays. Arrays are collections of items. A 2D array is formed when these items are arrays as well. In 2D arrays, the elements can be identified by their positions. They act as coordinates.

Bash only supports one-dimensional numerically indexed arrays as well as associative arrays. However, we can still implement them as follows:

Example:

#!/bin/bashecho "------Associative array------"declare -A arrA=([0,0]=Mercury [0,1]=Venus [1,0]=Earth [1,1]=Mars)echo "${arrA[@]}"for i in "${!arrA[@]}"do echo "$i -> ${arrA[$i]}"done

Since Bash doesn’t support 2D arrays, we can still implement them using the concept of 2D arrays and the other utilities Bash has on offer. For 2D associative arrays, the indices used are simply strings acting as keys. We can generate the keys in a loop.

Conclusion

  • Bash arrays are of two types- associative and indexed.

  • We have multiple ways of declaring and initializing an associative array.

  • Using the unset command, we can delete the elements as well as the entire associative array.

  • Bash doesn’t support 2D arrays but we have learned how we can implement the same.

adding elements to an associative array
initialize an associative array
appending elements to an associative array
implement 2D arrays
associative array using loops
declare an associative array
get the list of keys
get the list the values