In this lesson, you will learn how to use associative arrays to link descriptive names to specific configuration values, making your scripts much easier to manage.
Why Use Associative Arrays?
Up until now, you have likely worked with standard arrays, which use numbers (indices) to store data. While useful for lists, they become clunky when you need to store configuration settings—like mapping a server name to its specific IP address or a user role to a file path. Associative arrays allow you to use strings as keys, acting like a dictionary where you look up a value by its name instead of its position.
Declaring and Populating
In Bash, you must explicitly declare an associative array using the declare -A command. Without this flag, Bash will treat your keys as numbers, which will cause your script to fail.
Here is how you define a simple configuration map for environment settings:
# Declare the associative array
declare -A environment_paths
# Assign key-value pairs
environment_paths["production"]="/var/www/html/prod"
environment_paths["staging"]="/var/www/html/stage"
environment_paths["dev"]="/home/user/dev"
Retrieving Configuration Data
Once defined, you can access the value associated with a key by using the ${array_name[key]} syntax. This is incredibly powerful for cleaning up complex logic. Instead of writing long if-else blocks or case statements to determine which directory to use, you can simply perform a lookup:
# Set the current environment variable
env_mode="staging"
# Look up the path using the key
target_dir="${environment_paths[$env_mode]}"
echo "Deploying to: $target_dir"
If you try to access a key that hasn't been defined, Bash will return an empty string. This allows you to easily handle configuration defaults by checking if the value exists before proceeding.
By mapping human-readable keys to technical values, you eliminate the "magic strings" scattered throughout your scripts and create a centralized, readable configuration system that is much simpler to maintain as your project grows.
Key Takeaway: Associative arrays transform your configuration management by replacing complex conditional logic with direct, key-based lookups.