1

I want to get effect like bellow but I do not know how:

$> A='/dir'
$> B="$A/bin"
$> echo $B
/dir/bin
$> A='/other'
$> echo $B
/other/bin

any ideas?

  • Variables are evaluated at the time you use them in an assignment, not delayed until echo is called. . What about just inserting B="$A/bin" before the second echo, that should get you your result You could look at functions, but it is unclear if that is something you are looking for or not. Why do you need this, just to echo? Some other context? – Anthon Mar 9 '15 at 13:53
1

Ksh93 has a restricted form of this, where a variable can be an indirect reference to another variable:

$ A=/dir
$ typeset -n B=A
$ echo $B
/dir
$ A=/other
$ echo $B
/other

None of the usual shells have variables whose expansion occurs twice. Bash has an indirect refernce feature similar to the one in ksh, but with different syntax: you need to specify that you want an indirect reference at the time of access, not at the time of definition.

$ A=/dir
$ B=A
$ echo ${!B}
/dir
$ A=/other
$ echo ${!B}
/other

In general, the value of a variable only changes when you assign to it. If you want something that's recomputed every time you access it, retrieve the output of a command.

If what you want is to dynamically change the value of variables used by other programs, such as PATH and LD_LIBRARY_PATH, this is impossible, no matter what advanced feature the shell has. Once a program is started, its environment variables are the ones it received when it started; changing the value in a shell won't affect values in a process that is already running.

If you want to change the values of these variables based on some events, you can do so by running shell code. For example, you can make bash run some code every time it displays a prompt or when the current directory changes. Again, that won't affect programs that are already running.

0

If you want something like a template variable you can eval the expansion...

A=/dir
B=\$A/bin
eval echo $B

A=/other
eval echo $B
0

Variables don't behave like that. What you want is a function:

B () {
    echo "$A/bin"
}

A=/dir
echo $(B)

A=/other
echo $(B)
  • Nice, but can I use function name LD_LIBRARY_PATH or PATH? – Krzysztof Szewczyk Mar 9 '15 at 13:42
  • @KrzysztofSzewczyk: You can, but it won't change the value of the variables $PATH and $LD_LIBRARY_PATH. – choroba Mar 9 '15 at 13:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.