Bash Script – Variable Within a Variable Not Interpreted

bashshell-scriptvariable

I need to extract a path that is set within a config file, to use it in a bash script. This is how that path looks like inside said file:

DIR = "${HOME}/test/tmp"

I need to extract it without quotation marks, and this is how i do it:

TESTVAR="$(cat /home/user/path/to/file.conf | grep ^DIR | grep -o '".*"' | tr -d '"')"

The problem is that commands don't interpret ${HOME} variable "properly". Let's say i call echo $TESTVAR – as a result, instead of this:

/home/user/test/tmp

i get that:

${HOME}/test/tmp

so i can't use it as a parameter of commands inside a script!

Pretty please?

Best Answer

Expansions don't get recursively applied. Doing that would make it impossible to handle arbitrary data with dollar signs embedded. (A related matter is that quotes and redirection and other operators are also just regular characters after expansions.)

A somewhat usual custom is to have config files like that as actual shell script, so (like the ones in Debian's /etc/default), so the file would be

DIR="${HOME}/test/tmp"

and you'd read it with

. configfile

though of course that has the problem that the file is a full shell script, must conform to the shell syntax and the config can run arbitrary commands.

Another possibility would be to run the file through envsubst, e.g. with the file in your question, envsubst < configfile would output:

DIR = "/home/me/test/tmp"

or you could use envsubst '$HOME $OTHERĀ $VARS' to expand just some particular ones.

Note that unlike a shell script would do, envsubst doesn't read any assignments from the input file. E.g. the value of ROOTPATH used on the second line is the one envsubst gets from the environment, it has nothing to do with the "assignment" on the first line:

ROOTPATH=/something/$USER
LOGPATH=$ROOTPATH/logs
Related Question