Assuming that you are using the bash
shell:
$ source ./file
$ echo "$VAR1"
ABCDEF
$ var=VAR1
$ echo "${!var}"
ABCDEF
By using ${!var}
you use variable indirection in bash
. The value of the variable var
is used to get the name of the variable to expand.
In bash
you could also use a name reference variable:
$ source ./file
$ echo "$VAR1"
ABCDEF
$ declare -n var="VAR1"
$ echo "$var"
ABCDEF
Here, the var
variable refers to the VAR1
variable, so $var
will expand to whatever $VAR1
expands to.
Name references are originally a ksh
feature, and in that shell they are declare with typeset -n
.
Name references are extremely useful fo passing references to arrays in calls to shell functions.
In any sh
shell:
$ . ./file
$ echo "$VAR1"
ABCDEF
$ var=VAR1
$ eval "echo \"\$$var\""
ABCDEF
The eval
utility takes a string which it will re-evaluate. Here, we give it the string echo "$VAR1"
(after expansion of $var
).
The issue with eval
is that it's easy to introduce errors or vulnerabilities with it, by carelessly creating its argument string.