Last active
November 28, 2022 21:04
-
-
Save bng44270/57bd55de62281f41f3bd6cb01fa41966 to your computer and use it in GitHub Desktop.
Parse config files in Bash
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
################################################## | |
# | |
# Read text-based config files | |
# | |
# File Format: | |
# | |
# <Parameter Name><WHITESPACE><Parameter Value> | |
# | |
# File Sample (config.txt): | |
# | |
# DATADIR /path/to/data | |
# SESSIONS sessions.db | |
# | |
# Usage: | |
# | |
# $ eval $(configfile config.txt) | |
# $ echo $CONF_DATADIR | |
# /path/to/data | |
# $ echo $CONF_SESSIONS | |
# sessions.db | |
# | |
################################################## | |
configfile() { | |
if [ -f $1 ]; then | |
while read line; do | |
CONFIG_KEY="$(awk '{ print $1 }' <<< "$line")" | |
CONFIG_VAL="$(awk '{ print gensub(/^'"$CONFIG_KEY"'[ \t]+(.*)$/,"\\1","g",$0) }' <<< "$line")" | |
echo "CONF_${CONFIG_KEY}=\"${CONFIG_VAL}\"" | |
done < $1 | |
else | |
echo "File Not Found ($1)" | |
fi | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment