BASH

Parsing INI-like Configuration Files in Bash

Parse INI-style configuration files in Bash to load key-value pairs into script variables, supporting sections, comments, and dynamic configuration loading.

#!/bin/bash

# Define the configuration file
CONFIG_FILE="config.ini"

# Create a dummy config.ini for demonstration if it doesn't exist
if [ ! -f "$CONFIG_FILE" ]; then
  echo "; This is a comment
[database]
host=localhost
port=3306
user=dbuser
password=dbpass

[application]
name=MyApp
environment=production
loglevel=info" > "$CONFIG_FILE"
  echo "Created a sample $CONFIG_FILE."
fi

# Function to parse INI file
parse_ini_file() {
  local ini_file="$1"
  local section=default
  
  while IFS='=' read -r key value || [[ -n "$key" ]]; do
    # Remove leading/trailing whitespace
    key=$(echo "$key" | xargs)
    value=$(echo "$value" | xargs)

    # Skip comments and empty lines
    [[ "$key" =~ ^\s*# ]] && continue
    [[ "$key" =~ ^\s*; ]] && continue
    [[ -z "$key" ]] && continue

    # Handle sections: [section_name]
    if [[ "$key" =~ ^\[(.*)\]$ ]]; then
      section="${BASH_REMATCH[1]}"
      continue
    fi

    # Export key-value pairs as variables prefixed with section_ (uppercase)
    VAR_NAME="$(echo "${section^^}_${key^^}" | sed 's/[^A-Z0-9_]/_/g')"
    export "$VAR_NAME"="$value"
    echo "Loaded: $VAR_NAME = $value"

  done < "$ini_file"
}

# Call the parser function
parse_ini_file "$CONFIG_FILE"

echo "
--- Loaded Configuration ---"
# Example of accessing loaded variables
echo "DB Host: $DATABASE_HOST"
echo "App Name: $APPLICATION_NAME"
echo "Environment: $APPLICATION_ENVIRONMENT"

# Accessing a variable that might not exist for demonstration
echo "Non-existent variable: $DATABASE_NONEXISTENT_KEY (empty if not found)"

echo "Script finished."
How it works: This script provides a simple INI-like configuration file parser in Bash. It reads a configuration file line by line, handling comments, empty lines, and sections. Key-value pairs within each section are converted into environment variables, prefixed with the uppercase section name (e.g., `[database]` host becomes `DATABASE_HOST`). This allows scripts to easily load and use configurations from external `.ini` files, making them more modular and easier to manage across different environments without hardcoding values.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs