user3246938
user3246938

Reputation: 89

concatenate variables in a bash script

Hi I would like to set a variable by concatenating two other variables.

Example

A=1
B=2
12=C

echo $A$B

desired result being C

however the answer I get is always 12

Is it possible?

UPDATED Example

A=X
B=Y
D=$A$B

xy=test

echo $D

desired result being "test"

Upvotes: 0

Views: 101

Answers (3)

bryn
bryn

Reputation: 3325

What you are trying to do is (almost) called indirection: http://wiki.bash-hackers.org/syntax/pe#indirection

...I did some quick tests, but it does not seem logical to do this without a third variable - you cannot do concatenated indirection directly as the variables/parts being concatenated do not evaluate to the result on their own - you would have to do another evaluation. I think concatenating them first might be the easiest. That said, there is a chance you could rethink what you're doing. Oh, and you cannot use numbers (alone or as the starting character) for variable names.

Here we go:

cake="cheese"

var1="ca"
var2="ke"

# this does not work as the indirection sees "ca" and "ke", not "cake". No output.
echo ${!var1}${!var2}

# there might be some other ways of tricking it to do this, but they don't look to sensible as indirection probably needs to work on a real variable.
# ...this works, though:
var3=${var1}${var2}
echo ${!var3}

Upvotes: 1

legends2k
legends2k

Reputation: 32884

Since 12 is not a valid variable name, here's an example with string variables:

> a='hello'
> b='world'
> declare my_$a_$b='my string'
> echo $my_hello_world
my string

Upvotes: 2

Etan Reisner
Etan Reisner

Reputation: 80921

It looks like you want indirect variable references.

BASH allows you to expand a parameter indirectly -- that is, one variable may contain the name of another variable:

# Bash
realvariable=contents
ref=realvariable
echo "${!ref}"   # prints the contents of the real variable

But as Pieter21 indicates in his comment 12 is not a valid variable name.

Upvotes: 2

Related Questions