Getting environment variable value in unix

I have a properties file for setting some environment variables:

mydata.properties: VAR1=Data1 VAR2=Data2 

Now I want to define a new variable VAR3, which can contain VAR1 or VAR2, for example:

 mydata.properties: VAR1=Data1 VAR2=Data2 VAR3=VAR2 

To make these variables available for my bash session, I use 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 original VAR2 variable, for example:

 Value of VAR3 is Data2 

I tried different options like

echo "Value of VAR3 is $$VAR3"

This gives me an undesirable result.

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

This gives me an error like Value of ${$VAR3}: bad substitution

Please help me how to get this result.

+4
source share
5 answers

If you really need to expand the variable that VAR3 points to (instead of starting from VAR3 to VAR2), you can use the indirect change of the variable with ${!varname} :

 $ VAR1=Data1 $ VAR2=Data2 $ VAR3=VAR2 $ echo "${!VAR3}" Data2 
+13
source

I do not use bash, but

 mydata.properties: VAR1=Data1 VAR2=Data2 VAR3=$VAR2 

must do it. Note the extra $ infront from var2 in the last line.

+2
source

You might want to get used to this:

 VAR3=${VAR2} 

This is the same as VAR3=$VAR2 , but when you use variables embedded in other text (for example, VAR3=${VAR2}_foo ), you will need {} , so we recommend using them by default.

+1
source

Do you want to

 VAR2=$VAR3 

then

 echo "Value of VAR3 is $VAR3" 

Note the single $ in both places. You use $ to refer to the value of variables, so you need to use it when assigning a value to VAR2 and when printing its value in the echo command

0
source

I think you want to know how to make a link in BASH. The syntax can be quite complicated. It includes using eval and echo to set the value:

 VAR2=Data2 VAR3=VAR2 #Reference! echo "The value of $VAR3 is $(eval echo \$$VAR3)" 

It is better to use hash arrays instead of using links directly:

 REF[VAR3]=$VAR2 echo "The value of VAR3 = ${REF[VAR3]}" 

Or, as others point out, you could just do this:

 VAR3="$VAR2" 

if you just want to set $VAR3 the same as $VAR2 and you don't need links.

0
source

Source: https://habr.com/ru/post/1490500/


All Articles