Reputation: 13248
I have a property file having multiple key value pairs. Some of the values uses previously defined keys. Following is the sample
xpath=abc/temp.txt
fullpath=$HOME/$xpath
...
I want to parse this file line by line and print the lines along with resolving env variables like $HOME as well as earlier defined variables like $xpath
The expected output is
xpath=abc/temp.txt
fullpath=tempuser/abc/temp.txt
...
How do I expand the variables in this way in a bash script
Upvotes: 1
Views: 74
Reputation: 39414
Since the assignments are valid bash, source settings.env
suffices to evaluate them. However, you also want to print the assignments, so more trickery required:
PS4="\000" source <(echo 'set -x'; cat settings.env; echo '{ set +x; } 2>/dev/null')
This trick uses the bash debugging facility of set -x
to print the output of each assignment as it's performed. In words:
PS4="\000"
removes the debugging prompt, which by default is +
<()
creates a new file, by the pipeline contained within the parenthesesset -x
enables debuggingcat settings.env
inserts your settings{ set +x; } 2>dev/null
disables debugging, without outputting it doing soUpvotes: 0
Reputation: 14217
If you want to parse line by line and interpret the variables, You maybe want to use the eval
for evaluating the String, like:
while IFS='=' read -r key value
do
key=$(echo $key | tr '.' '_')
if [[ ! -z $key ]]
then
v=`eval "echo ${value}"`
eval "${key}='${v}'"
echo "${key}=${v}"
fi
done < "my.properties"
In the above code snippet, use the eval
with echo
to interpret the variables
.
Upvotes: 1