0

I have a variable (var) which return value as VAR1 ($var has the value VAR1). There is an input file which has VAR1 defined (VAR1=ABCDEF)

How can I use echo to get the value ABCDEF using $var??

I tried echo $(echo $var) and many other options, but I always get output as VAR1 or echo VAR1 but never ABCDEF. I used source in file with VAR1 declared, tried in command prompt etc.

Kusalananda
  • 333,661
shashank barki
  • 5
  • 1
  • 1
  • 3

2 Answers2

6

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.

Kusalananda
  • 333,661
3

Assuming you are using bash, you can accomplish this easily with an indirect reference:

$ foo=bar
$ bar=magicword
$ printf "%s\n" "${!foo}"
magicword

The syntax $var (or ${var}) yields the contents of the variable var.

The syntax ${!var} yields the contents of the variable named in var.

DopeGhoti
  • 76,081