Creating a Practical Configuration Manager
Now that you understand how to create and manipulate key-value arrays, let's build something practical. In this step, you'll create a simple configuration manager that loads settings from a config file, stores them in a key-value array, and allows you to access them.
Step 1: Create a Configuration File
First, let's create a configuration file with some sample settings:
- Create a new file called
app_config.txt
in the /home/labex/project
directory
- Add the following content to the file:
database_host=localhost
database_port=3306
database_user=admin
database_password=secret123
app_name=MyAwesomeApp
debug_mode=true
max_connections=100
- Save the file
Step 2: Create the Configuration Manager Script
Now, let's create a script that will read this configuration file and store its contents in a key-value array:
- Create a new file called
config_manager.sh
in the /home/labex/project
directory
- Add the following code to the file:
#!/bin/bash
## Define the path to the configuration file
CONFIG_FILE="/home/labex/project/app_config.txt"
## Declare a key-value array for the configuration
declare -A config
## Function to load configuration from file
load_config() {
local file=$1
## Check if the file exists
if [[ ! -f "$file" ]]; then
echo "Error: Configuration file '$file' not found."
return 1
fi
## Read the file line by line
while IFS='=' read -r key value; do
## Skip empty lines and comments
if [[ -z "$key" || "$key" == \#* ]]; then
continue
fi
## Store the key-value pair in the array
config["$key"]="$value"
done < "$file"
echo "Configuration loaded successfully from '$file'"
return 0
}
## Function to get a configuration value
get_config() {
local key=$1
local default=$2
## Check if the key exists
if [[ -v config["$key"] ]]; then
echo "${config["$key"]}"
else
echo "$default"
fi
}
## Function to display all configuration
display_config() {
echo "--- Configuration Settings ---"
for key in "${!config[@]}"; do
echo "$key = ${config[$key]}"
done
}
## Load the configuration
load_config "$CONFIG_FILE"
## Display all configuration settings
display_config
## Example of getting specific configuration values
echo -e "\n--- Example Usage ---"
db_host=$(get_config "database_host" "127.0.0.1")
db_port=$(get_config "database_port" "5432")
db_user=$(get_config "database_user" "root")
db_pass=$(get_config "database_password" "")
app_name=$(get_config "app_name" "DefaultApp")
debug_mode=$(get_config "debug_mode" "false")
echo "Database connection: $db_user@$db_host:$db_port"
echo "Application name: $app_name"
echo "Debug mode: $debug_mode"
## Example of getting a non-existent value (will use default)
timeout=$(get_config "connection_timeout" "30")
echo "Connection timeout: $timeout (default value used)"
- Save the file (Ctrl+S or File > Save)
- Make the script executable:
chmod +x config_manager.sh
- Run the script:
./config_manager.sh
You should see output similar to this:
Configuration loaded successfully from '/home/labex/project/app_config.txt'
--- Configuration Settings ---
database_host = localhost
database_port = 3306
database_user = admin
database_password = secret123
app_name = MyAwesomeApp
debug_mode = true
max_connections = 100
--- Example Usage ---
Database connection: admin@localhost:3306
Application name: MyAwesomeApp
Debug mode: true
Connection timeout: 30 (default value used)
Understanding the Configuration Manager
The script you've created does several important things:
- It reads key-value pairs from a configuration file
- It stores these pairs in a key-value array
- It provides functions to:
- Load configuration from a file
- Get specific configuration values with default fallbacks
- Display all configuration settings
This pattern is commonly used in real-world applications to manage configuration settings. The key benefits are:
- Centralized configuration: All settings are in one place
- Default values: If a setting is missing, a default value can be used
- Easy access: Settings can be accessed by name
- Flexibility: Configuration can be updated without changing the script
This example demonstrates how key-value arrays can be used to solve practical problems in shell scripting. You could extend this by adding functions to save changes back to the configuration file or to validate settings.