Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting value of environment variable in unix

Tags:

bash

unix

I have a properties file to set some environment variables say:

mydata.properties:

VAR1=Data1
VAR2=Data2

Now I want to define a new variable called VAR3 that can hold either VAR1 or VAR2 like:

mydata.properties:

VAR1=Data1
VAR2=Data2
VAR3=VAR2

To make these variables to be available to my bash session I am using this command

source mydata.properties

Now my requirement is to print the value for VAR3 so that it can print the internal data of the sourced VAR2 variable like:

Value of VAR3 is Data2

I tried different options like

echo "Value of VAR3 is $$VAR3"

This gives me junk output.

or echo "Value of VAR3 is ${$VAR3}"

This give me error as Value of ${$VAR3}: bad substitution

Please help me how to get this output.

like image 811
Chaitanya Avatar asked Dec 03 '22 22:12

Chaitanya


1 Answers

If you really need to expand the variable that VAR3 points to (instead of just setting VAR3 to the value of VAR2 to begin with), you can use indirect variable expansion with ${!varname}:

$ VAR1=Data1
$ VAR2=Data2
$ VAR3=VAR2
$ echo "${!VAR3}"
Data2
like image 119
Gordon Davisson Avatar answered Jan 02 '23 15:01

Gordon Davisson