← Back to all snippets
BASH

Extract Specific Configuration Values from Files

A bash script to parse and extract specific key-value pairs from configuration files like .env or INI files, useful for scripting deployment or environment setup.

#!/bin/bash

# Configuration
CONFIG_FILE=".env"
TARGET_KEY="APP_ENV"

# Check if config file exists
if [ ! -f "$CONFIG_FILE" ]; then
    echo "Error: Configuration file '$CONFIG_FILE' not found."
    exit 1
fi

# Extract the value using grep and cut/awk
# This assumes KEY=VALUE format and ignores comments/empty lines
VALUE=$(grep "^$TARGET_KEY=" "$CONFIG_FILE" | head -n 1 | cut -d '=' -f 2-)

# Alternative with awk (more robust for spaces, comments):
# VALUE=$(awk -F'=' -v key="$TARGET_KEY" '$1 == key {print $2; exit}' "$CONFIG_FILE")

if [ -n "$VALUE" ]; then
    echo "Value of $TARGET_KEY: $VALUE"
else
    echo "Key '$TARGET_KEY' not found in '$CONFIG_FILE'."
fi
How it works: This script demonstrates how to extract a specific configuration value from a file formatted as `KEY=VALUE`, common in `.env` files for web projects. It uses `grep` to find the line containing the key and `cut` to isolate the value. An `awk` alternative is also provided for more robust parsing of files with potential spaces or comments. This is extremely useful for automating deployments, CI/CD pipelines, or environment setup where configuration values need to be read programmatically.

Need help integrating this into your project?

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

Hire DigitalCodeLabs