0

How to deal with assigning variables as below? I am assigning value var1=1 next assigning var2=$var1, but every time I change value of var1, echo $var2 shows always old value i.e

# var1=1 # var2=$var1 # echo $var2 1 
# var1=2 # echo $var2 1 

2 Answers 2

1

This is a common miss-conception about how many/most programming languages work.

In imperative languages (bash/C/Java/python....), the = operator does not work the same way as in maths.

a=1 means put 1 into a (overwriting what was there).

I.E.

var1=1 # var1 ← 1 #overwrite var1 with 1 var2=$var1 # var2 ← $var1 #overwrite var2 with evaluation of $var1 (i.e 1) var1=2 # var1 ← 2 #overwrite var1 with 2 stdout ←← $var2 #append $var2 to stdout 

Therefore

# var1 var2 var1=1 # 1 n/a var2=$var1 # 1 1 var1=2 # 2 1 
1

If you assign the value of var1 to var2 you have two independent variables var1 and var2 which just happen to have the same values.

You could use a variable var2 declared with the nameref attribute for a reference to var1.

$ var1=1 $ declare -n var2=var1 $ echo "$var2" 1 $ var1=2 $ echo "$var2" 2 $ var2=3 $ echo "$var2 $var1" 3 3 

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.