Skip to content

Instantly share code, notes, and snippets.

@bng44270
Last active November 28, 2022 21:04
Show Gist options
  • Save bng44270/57bd55de62281f41f3bd6cb01fa41966 to your computer and use it in GitHub Desktop.
Save bng44270/57bd55de62281f41f3bd6cb01fa41966 to your computer and use it in GitHub Desktop.
Parse config files in Bash
##################################################
#
# 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