How do I set an environment variable in tcsh that dynamically references other env vars?

0

1

I'm using tcsh here, and am trying to get an environment variable that references another one dynamically...

I want to be able to do the following, and I'm sure I've seen it done before elsewhere:

$ setenv A abc
$ setenv B a_is_${A}
$ echo $B

> a_is_abc

$ setenv A def
$ echo $B

> a_is_def

However, when $B is initially set, it evaluates $A at that time, rather than keeping it to be evaluated when actually needed. Meaning that I get the same result for 'echo $B' both times.

Any idea how to do this?

Thanks

Hugh

Posted 2010-10-17T17:24:14.260

Reputation: 1 131

Answers

0

I think I've got this one figured out...

$ setenv A abc
$ setenv B 'a_is_${A}'
$ echo $B

> a_is_$A

$ eval echo $B

> a_is_abc

$ setenv A def
$ eval echo $B

> a_is_def

It's all about using a combination of 'eval' with having quotes around the variable in the first place...

In my case, I'm using it like this:

set sw_version '${SW_VERSION_MAJOR}.${SW_VERSION_MINOR}'
set sw_plugin_path /path/to/plugins/for/sw/${sw_version}/plugins


if ( $?SW_PATH ) then
    setenv SW_PATH ${sw_plugin_path}:$SW_PATH
else
    setenv SW_PATH ${sw_plugin_path}
endif

And then, in the wrapper script for the software, I just have:

eval setenv SW_PATH $SW_PATH

Which means that I can change SW_VERSION_MAJOR or SW_VERSION_MINOR at any time, and SW_PATH will change accordingly without having to be reset from scratch.

Hugh

Posted 2010-10-17T17:24:14.260

Reputation: 1 131

1

I don't think you can do this in shell. B will always take the value of A when B is set, not when B is read.

The only place I've seen what you've described is in Makefiles, where it would keep the expression and evaluate it at the time it was read.

Rich Homolka

Posted 2010-10-17T17:24:14.260

Reputation: 27 121

Just to let you know - I think I got this one figured out - see my answer to my own question if you're interested... – Hugh – 2010-10-31T16:43:31.687