Associative Arrays in Bash

Bash, the command-line shell and scripting language for Unix-based systems, comes equipped with a powerful data structure known as Associative Arrays in Bash. These arrays provide a way to store key-value pairs, allowing for efficient data manipulation in shell scripts. In this blog post, we’ll explore the basics and demonstrate their practical applications with examples.

Associative Arrays in Bash
Associative Arrays in Bash

Declaring Associative Arrays

To declare an associative array in Bash, use the following syntax:

declare -A my_array

Here, -A signifies that we are creating an associative array named my_array. Unlike traditional arrays in Bash, associative arrays are indexed by keys rather than numerical indices.

Populating and Accessing Values

#!/bin/bash

# Declare an associative array
declare -A my_array

# Populating the array
my_array["name"]="John"
my_array["age"]=25
my_array["city"]="New York"

# Accessing values
echo "Name: ${my_array["name"]}"
echo "Age: ${my_array["age"]}"
echo "City: ${my_array["city"]}"

You can also populate the array using the syntax below

declare -A SERVERS=(
    ["web"]="webserver.justgeek.io"
    ["data"]="data.justgeek.io"
    ["app"]="app.justgeek.io"
  )

Iterating Through an Associative Array

# Iterating through keys
for key in "${!my_array[@]}"; do
  echo "Key: $key, Value: ${my_array[$key]}"
done

Deleting a Key-Value Pair

key_to_delete="city"
unset my_array["$key_to_delete"]
echo "Deleted key '$key_to_delete'"

Here is the practical script using Associative arrays in the script, please read through the comments which explains the script.

# This line specifies that script should be executed using the Bash shell
#!/bin/bash

# Here, an associative array named SERVERS is declared and initialized. 
# It contains key-value pairs where the keys are server identifiers 
# Keys are ("web", "data", "app") and the values are the 
# corresponding server addresses 
# values are ("web.justgeek.io", "data.justgeek.io", "app.justgeek.io").


declare -A SERVERS=(
    ["web"]="web.justgeek.io"
    ["data"]="data.justgeek.io"
    ["app"]="app.justgeek.io"
)

# This part of the script checks if there is at least one command-line 
# argument ($1). 
# If not, it prints a usage message and exits with an error status (1).

if [ -z "$1" ]; then
    echo "Usage: ./server <server_key>"
    exit 1
fi

# If there is a command-line argument, it assigns the first argument 
# to the variable SERVER_KEY.

SERVER_KEY=$1

# This section checks if the value associated with the specified 
# SERVER_KEY exists in the SERVERS associative array. 
# If not, it prints an error message and exits with an error status (1).
# This condition checks if the value associated with the given SERVER_KEY
# is empty or not. 

# In Bash, if the key doesn't exist in the associative array, the value
# associated with that key will be empty. 
# Therefore, the -z test checks whether the value is empty or not.
# This approach works because associative arrays in Bash return an empty
# string for keys that do not exist. 
# The script doesn't need to iterate through the entire array; 
# it directly checks if the value for the specified key is empty.

# Check if the specified server key is in the associative array
if [ -z "${SERVERS[$SERVER_KEY]}" ]; then
    echo "Error: Server not found in the list."
    exit 1
fi

# If the specified server key is found in the array, 
# it uses the ssh command to connect to the corresponding server address

# Connect to the selected server
ssh "$${SERVERS[$SERVER_KEY]}"

Let’s get in the detailed explanation of the script above.

Here, an associative array named SERVERS is declared and initialized. It contains key-value pairs where the keys are server identifiers (“web”, “data”, “app”) and the values are the corresponding server addresses (“web.justgeek.io”, “data.justgeek.io”, “app.justgeek.io”).

Associative arrays in Bash provide a flexible and efficient way to manage data in scripts. Whether you’re storing configuration parameters, managing user information, or processing key-value pairs, associative arrays are a valuable tool in your Bash scripting arsenal. Mastering their use can significantly enhance the readability and functionality of your scripts. Experiment with these examples and unlock the full potential of associative arrays in your Bash programming journey.

Leave a Comment