BASH

Dynamically Updating Configuration File Values

Automate the modification of specific key-value pairs within configuration files (like `.env`) using Bash and `sed` for environment-specific settings.

#!/bin/bash

# --- Configuration ---
CONFIG_FILE=".env" # Example: Laravel .env file

# --- Functions ---
update_config_value() {
    local KEY=$1
    local NEW_VALUE=$2
    
    if [ -z "$KEY" ] || [ -z "$NEW_VALUE" ]; then
        echo "Error: Both KEY and NEW_VALUE must be provided."
        echo "Usage: update_config_value <KEY> <NEW_VALUE>"
        return 1
    fi
    
    if [ ! -f "$CONFIG_FILE" ]; then
        echo "Error: Configuration file '$CONFIG_FILE' not found."
        return 1
    fi
    
    # Use sed to find and replace the value for the given key.
    # -i: In-place editing
    # s/: substitute command
    # ^$KEY=.*: Matches lines starting with KEY= and any subsequent characters
    # $KEY=$NEW_VALUE: Replaces with KEY=NEW_VALUE
    # g: Global replacement (though typically only one line matches)
    # ^...$: Ensures it only matches at the beginning of the line
    
    # Check if the key exists before attempting to replace
    if grep -q "^$KEY=" "$CONFIG_FILE"; then
        sed -i "s/^$KEY=.*/$KEY=$NEW_VALUE/" "$CONFIG_FILE"
        if [ $? -eq 0 ]; then
            echo "Updated '$KEY' to '$NEW_VALUE' in '$CONFIG_FILE'."
        else
            echo "Failed to update '$KEY' in '$CONFIG_FILE'."
            return 1
        fi
    else
        # If the key doesn't exist, append it
        echo "Key '$KEY' not found. Appending '$KEY=$NEW_VALUE' to '$CONFIG_FILE'."
        echo "$KEY=$NEW_VALUE" >> "$CONFIG_FILE"
    fi
}

# --- Main Execution ---
echo "--- Updating Environment Configuration ---"

# Example usage:
update_config_value "APP_ENV" "production"
update_config_value "DB_HOST" "192.168.1.100"
update_config_value "APP_DEBUG" "false"

# Example for a new key (will be appended)
update_config_value "NEW_FEATURE_TOGGLE" "true"

echo "Configuration update process finished."

# Verify changes (optional)
echo ""
echo "--- Current Configuration Snippet ---"
grep -E "APP_ENV|DB_HOST|APP_DEBUG|NEW_FEATURE_TOGGLE" "$CONFIG_FILE" || echo "No matches found."
How it works: This script provides a function to dynamically update or add key-value pairs in a configuration file, such as a `.env` file, commonly used in web projects. It leverages `sed` for in-place text replacement to modify existing values or appends new key-value pairs if they don't already exist, simplifying environment-specific configuration management.

Need help integrating this into your project?

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

Hire DigitalCodeLabs