Reputation: 10799
Consider the following Bash script:
$ A=35
$ echo $A
35
$ B=$A
$ echo $B
35
$ B=43
$ echo $B
43
$ echo $A
35
I declared a variable A
, assigned the value 35
to it, made B
equal to A
, and assigned the value 43
to B
. It appears that A
retains the value 35
after all this, so I'm guessing when you assign one variable in bash to another, it's copy by value, not copy by reference.
What I want to be able to do is change B
's value and have it reflected in A
(copy by reference). Or, in my real case, I simply don't want to incur the memory overhead of copy by value, as I know it's a large variable and don't want to store it twice in memory. Is there a way to do this in Bash?
Upvotes: 2
Views: 697
Reputation: 14940
You can reference another variable with
$ a=42
$ reference=a
$ echo ${!reference}
42
To change the value of the referenced variable
$ eval ${reference}=4
$ echo ${!reference}
4
echo $a
4
Upvotes: 3