Is it possible to use a variable by reference in bash scripting in the way it is done in C++?
Lets say I have a script like below:
#!/bin/bash
A="say"
B=$A
echo "B is $B"
A="say it"
echo "B is $B" # This does not get the new value of A but is it possible to using some trick?
You see in above script echo "B is $B outputs B is say even if the value of A has changed from say to say it. I know that reassignment like B=$A will solve it. But I want to know if it is possible that B holds a reference to A so that B updates it's value as soon as A updates. And this happens without reassignment that is B=$A. Is this possible?
I read about envsubst from Lazy Evaluation in Bash. Is following the way to do it?
A="say"
B=$A
echo "B is $B"
envsubst A="say it"
echo "B is $B"
And similar to C++, once you assign the value of a variable, there is no way to track where from the value came from. In shell all variables store strings. You can store variable name as a string inside another variable, which acts as the reference. You can use:
Bash indirect expansion:
Bash namereferences:
Evil
eval:Yes - store the name of the variable in
B, instead of the value.No,
envsubstdoes something different.