Skip to content

Instantly share code, notes, and snippets.

@makkes
Last active February 8, 2019 09:02
Show Gist options
  • Save makkes/bc48937090ffc542a4b08f96d0036f2e to your computer and use it in GitHub Desktop.
Save makkes/bc48937090ffc542a4b08f96d0036f2e to your computer and use it in GitHub Desktop.
Read properties files in Bash
read_props() {
local key
if [[ ! -r $1 ]] ; then
echo file $1 not readable
exit 1
fi
while IFS='=' read -r key value
do
if [[ -z ${key} ]] || [[ "${key}" =~ ^# ]] ; then
continue
fi
#key=$(echo $key | tr '.' '_')
props["$key"]="$value"
done < "$1"
}
resolve_placeholders() {
# resolve all placeholders of the form `${PROP}` with the
# given property `PROP` in `props`.
for i in "${!props[@]}" ; do
for placeholder in $(echo -en ${props[$i]} | grep -Po '\${.*?}') ; do
# remove surrounding ${} from the placeholder
placeholder=${placeholder#\$\{}
placeholder=${placeholder%\}}
props["$i"]=${props[$i]/\$\{$placeholder\}/${props[$placeholder]}}
done
done
}
# this is the resulting associative array
declare -A props
# now read all our properties files...
read_props 'src/main/resources/conf/default.properties'
read_props "src/main/resources/conf/prod/application.properties"
# ...and replace all placeholders of the form `my.prop=${my.another.prop}`
resolve_placeholders
# now `props` is filled with all properties from the files and placeholders resolved
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment