How do I correctly handle variable expansion in my config file?

0
8
Asked By CuriousCoder42 On

Hey folks! I've got a line in my config file that looks like this: `LOG_ROOT = ${HOME}/log`. In my script, I'm trying to read this entry and use it, but I'm running into issues with variable expansion when I write to the log file.

Here's a snippet of my script:
```bash
config_file="${1}";
mapfile -t config_entries < "${config_file}";
if (( ${#config_entries[*]} == 0 )); then
(( error_count += 1 ));
else
for entry in "${config_entries[@]}"; do
[[ -z "${entry}" ]] && continue;
[[ "${entry}" =~ ^# ]] && continue;
property_name="$(cut -d "=" -f 1 <<< "${entry}" | xargs)";
property_value="$(cut -d "=" -f 2- <<< "${entry}" | xargs)";
CONFIG_MAP["${property_name}"]="${property_value}";
done
fi
```
When I try to write to the log file, set -x shows I'm getting the expected output, but the variable `${HOME}` isn't expanding as I expect. Instead, I just see `${HOME}/log/debug.log`. How can I fix this?

2 Answers

Answered By ScriptGuru89 On

To make variable expansion work correctly in your setup, I'd suggest sourcing the config file directly. This allows bash to treat the assignments like regular variable assignments, which will help with expanding variables correctly. Also, ensure there are no spaces around the `=` in your config file; bash doesn’t like that. Just remember, if you want this to behave as a property file for other applications, sourcing might not be the way to go.

Answered By DevDude101 On

You don't need to end every line in your config file with a semicolon. Bash isn't particularly picky about that, and it might be causing some confusion. Just clean it up a little and you should be on the right track!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.