0

Here is the scenario:

The System is preset with the following Environment Variables:

INNER1=1
INNER2=2
INNER3=3

Now I have the file: values.properties

OUTER1=$INNER1
OUTER2=$INNER2
OUTER3=$INNER3

I also have a shell script named: run.sh

#!/bin/sh

PROPERTIES_FILE=values.properties

while IFS== read -r VAR1 VAR2
do
    export $VAR1=$VAR2
done < $PROPERTIES_FILE

Now the problem is, when I run the script, the following is exported:

OUTER1=$INNER1
OUTER2=$INNER2
OUTER3=$INNER3

But the desired result should be:

OUTER1=1
OUTER2=2
OUTER3=3

I want it to fully resolve the variable name when exporting it.

7
  • 2
    Why complicate things? Just . values.properties Commented Apr 22, 2020 at 0:43
  • How do you run that script? Or where do you use the exported variables? Commented Apr 22, 2020 at 0:58
  • 1
    For an extensive discussion of indirect expansion in bash, see BashFAQ #6. That said, if you trust your data to be valid code, I agree with Joseph that you should be running it as code explicitly (using the . operator, also aliased in bash under the name source). Commented Apr 22, 2020 at 1:56
  • @CharlesDuffy : While the OP tagged this as bash, the script is most likely not executed as bash script. Unfortunately, the OP did not tell us how he runs the script, but assuming that he runs it just by entering its path, it is run by sh. Commented Apr 22, 2020 at 7:01
  • 1
    @user1934428, the BashFAQ also covers POSIX sh and ksh. Commented Apr 22, 2020 at 11:33

1 Answer 1

0

You need to make use of shell parameter expansion. #!/bin/sh

PROPERTIES_FILE=values.properties

while IFS== read -r VAR1 VAR2
do
  export $VAR1="${!VAR2}"
done < $PROPERTIES_FILE

You may also need to change your values.properties file to:

OUTER1=INNER1
OUTER2=INNER2
OUTER3=INNER3

I hope this helps!

Sign up to request clarification or add additional context in comments.

1 Comment

In How to Answer, see the section Answer Well-Asked Questions, and the bullet point therein about questions that "have already been asked and answered many times before". Answering duplicates means that folks are less likely to see the more complete and extensively-vetted set of answers on the question's canonical instances. (Of course, you should feel encouraged to add a new answer on the canonical instance if the ones already there are missing something!)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.