1

I want to create a variable from multiple variables by concatenating their values. After that I want to update value in those nested child variables and see the change in the parent one. Something like this:

#!/bin/bash

a=123
b=abc

c=$a$b
echo $c # outputs 123abc

a=456
echo $c # outputs 123abc although I want 456abc

I'd like this to output 123abc and 456abc but instead I get 123abc and 123abc. Is it possible to achieve the behaviour I want in bash?

2
  • 1
    By doing c=$a$b, you're not assigning references of a and b to c, but you're assigning their values. Commented Dec 3, 2019 at 17:46
  • 4
    I suggest using a function instead of variable for nested variables like c() { echo "$a$b"; } and use it as $(c) in your script and you will get updated values all the time. Commented Dec 3, 2019 at 17:51

2 Answers 2

3

In BASH (4+) you can create reference of variables using declare -n so if you have:

a=123

And create a variable reference as:

declare -n c=a

then echo $c will print 123.

If you now change to a=789 then if you execute echo $c again you will get updated value of 789.

However this reference can be created for a single variable (or array) only, nor for combination of multiple variables.

As a simple work around consider using shell function for your usecase as this:

c() { echo "$a$b"; }

Then $(c) will always be dynamic and would always get you update value by concatenating values a and b.

Sign up to request clarification or add additional context in comments.

Comments

1

I think this is what you are looking for. Be careful though as eval use can be dangerous if you don't trust the input.

#!/bin/bash

a=123
b=abc

c="\${a}\${b}"
eval "echo $c"

a=456
eval "echo $c" 

Hope it helps!

3 Comments

Wasn't eval discouraged?
Yes. It is. As I pointed out. But its the best way to accomplish what OP wants
In an XY problem, the best way to solve Y is not necessarily a good way to solve X.

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.