I found using while IFS='=' read -r
to be a bit slow (I don't know why, maybe someone could briefly explain in a comment or point to a SO answer?). I also found @Nicolai answer very neat as a one-liner, but very inefficient as it will scan the entire properties file over and over again for every single call of prop
.
I found a solution that answers the question, performs well and it is a one-liner (bit verbose line though).
The solution does sourcing but massages the contents before sourcing:
#!/usr/bin/env bash
source <(grep -v '^ *#' ./app.properties | grep '[^ ] *=' | awk '{split($0,a,"="); print gensub(/\./, "_", "g", a[1]) "=" a[2]}')
echo $db_uat_user
Explanation:
grep -v '^ *#'
: discard comment lines
grep '[^ ] *='
: discards lines without =
split($0,a,"=")
: splits line at =
and stores into array a
, i.e. a[1] is the key, a[2] is the value
gensub(/\./, "_", "g", a[1])
: replaces .
with _
print gensub... "=" a[2]}
concatenates the result of gensub
above with =
and value.
Edit: As others pointed out, there are some incompatibilities issues (awk) and also it does not validate the contents to see if every line of the property file is actually a kv pair. But the goal here is to show the general idea for a solution that is both fast and clean. Sourcing seems to be the way to go as it loads the properties once that can be used multiple times.