BASH

Extract Value from Key-Value Configuration File

A bash script to parse a simple key-value configuration file and extract the specific value for a given key, useful for dynamically reading application settings into other scripts.

#!/bin/bash

# Extract a specific value from a key-value configuration file.
# Handles basic .ini or custom key=value formats, ignores comments.
# Usage: ./get_config_value.sh "config.ini" "DATABASE_HOST"

CONFIG_FILE="$1"
TARGET_KEY="$2"

if [ ! -f "$CONFIG_FILE" ]; then
  echo "Error: Configuration file not found at $CONFIG_FILE" >&2
  exit 1
fi

if [ -z "$TARGET_KEY" ]; then
  echo "Usage: $0 <config_file> <key>" >&2
  exit 1
fi

# Use grep to find the line, head to get the first match, sed to extract value, xargs to trim whitespace
VALUE=$(grep -E "^[[:space:]]*${TARGET_KEY}[[:space:]]*=" "$CONFIG_FILE" | head -n 1 | sed -E "s/^[[:space:]]*${TARGET_KEY}[[:space:]]*=(.*)/\1/" | xargs)

if [ -n "$VALUE" ]; then
  echo "$VALUE"
  exit 0
else
  echo "Key '$TARGET_KEY' not found or has no value in $CONFIG_FILE." >&2
  exit 1
fi
How it works: This script reads a configuration file (e.g., `.ini` or a custom key-value format) and efficiently retrieves the value associated with a specified key. It uses a combination of `grep` to locate the relevant line, `head` for the first match, `sed` to precisely extract the value after the equals sign, and `xargs` to trim any surrounding whitespace. This utility is invaluable for scripts that need to dynamically read and utilize specific application settings from configuration files.

Need help integrating this into your project?

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

Hire DigitalCodeLabs