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?
-
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!Jason Hu– Jason Hu2015-07-27 12:53:39 +00:00Commented Jul 27, 2015 at 12:53
Add a comment
|
1 Answer
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