0

Is there a way to change the contents of a string with variable expansion and have the contents update if the variable does?

Like so:

var1=0 # set var1
var2="$var1" # set var2 to var1
var1=1 # set var1 to something else and have var2 change as well?

I know this example will not work but it is just to show you guys what I'm trying to do.

Is there any way at all to accomplish this without always setting var1 before var2?

Thanks in advance

EDIT: Also, is it possible to do this with a variable that hasn't been set before the first one? Like so:

var2=$var1
var1=10
echo $var2

I want the output to be 10 but since var1 is not set when assigned to var2, the var2 will also be empty. Help

2 Answers 2

2

Check this: How can I use variable variables (indirect variables, pointers, references) or associative arrays?

One way:

var1=200
var2=var1
echo ${!var2}                                    
200
var1=100
echo ${!var2}
100
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah that is one way to do it but I'd prefer not to do it that way if possible since it, as it says in the FAQ itself, is a bad idea.
0

I think bash has no pointer concept.

So if I do this, I would write a function, e.g. setVar1, the func has one argument, which is the new value of var1. in this function, the new value would be set to var1 and var2

So you have to call the function when you want to set a value to var1.

Also, if var2 always has same value as var1, why not just use one variable?

2 Comments

This was just a simple example. In my script var1 refers to multiple variables that are set after var1
well ok, you know your requirement best. you could put the multiple variables into that function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.