TheWaterProgrammer
TheWaterProgrammer

Reputation: 8229

Updating variables by reference in bash script?

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"

Upvotes: 2

Views: 1003

Answers (1)

KamilCuk
KamilCuk

Reputation: 140960

Updating variables by reference in bash script?

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:

A="say"
B=A
echo "B is ${!B}"
A="say it"
echo "B is ${!B}"

Bash namereferences:

A="say"
declare -n B=A
echo "B is $B"
A="say it"
echo "B is $B"

Evil eval:

A="say"
B=A
eval "echo \"B is \$$B\""
A="say it"
eval "echo \"B is \$$B\""

Is this possible?

Yes - store the name of the variable in B, instead of the value.

envsubst from Lazy Evaluation in Bash. Is following the way to do it?

No, envsubst does something different.

Upvotes: 5

Related Questions