2

I have a .sh script which uses environment variables I export before. I would like my variables to be like this: VAR1="${libDir}/test" so that in my script, the ${libDir} will be replaced with some value. I declared my export like below: export VAR1="${libDir}/test" but in my script the libDir is not taken into account at all. Can I do it this way?

1
  • you are substituting your value in current environment. but i have to let you know, that what you are trying to do is extremely confusing and dangerous. you try to make even variable to be dynamically scoped! if your scripts grow up to 5 files. you will be the only one maintaining it since no other people is able to and willing to maintain that mess! Commented Jul 27, 2015 at 12:53

1 Answer 1

2

No, you can't have a variable that contains a variable reference that gets substituted in a "delayed" fashion:

$ libDir=foo
$ VAR1="${libDir}/test"
$ libDir=bar
$ echo "$VAR1"
foo/test

You could get around this using eval, but you shouldn't.

However, a function will do exactly what you want, with the price of a touch extra syntax:

$ var1() {
    echo "${libDir}/test"
}
$ libDir=foo
$ echo "$(var1)"
foo/test
$ libDir=bar
$ echo "$(var1)"
bar/test
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.