27

I have a bash script I am having some issues with concatenating 2 variables to call a 3rd.

Here is a simplification of the script, but the syntax is eluding me after reading the docs.

server_list_all="server1 server2 server3";
var1 = "server";
var2 = "all";

echo $(($var1_list_$var2));

This is about as close as I get to the right answer, it acknowledges the string and tosses an error on tokenization.

syntax error in expression (error token is "server1 server2 server3....

Not really seeing anything in the docs for this, but it should be doable.

EDIT: Cleaned up a bit

1

2 Answers 2

45

The Bash Reference Manual explains how you can use a neat feature of parameter expansion to do some indirection. In your case, you're interested in finding the contents of a variable whose name is defined by two other variables:

server_list_all="server1 server2 server3"
var1=server
var2=all
combined=${var1}_list_${var2}

echo ${!combined}

The exclamation mark when referring to combined means "use the variable whose name is defined by the contents of combined"

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

4 Comments

Thanks so much! I tried to one shot it one line using the !, but kept getting a substitution error. So you have to use an intermediate variable. Thanks again!
So is there really no way to do this without creating a new variable?
@TimothySwan, eval "echo `echo \\$\\{${var1}_list_${var2}\}`" but that's just nasty.
Can you concatenate var1 and var2 and set that value to combined in a way similar to this: combined=${var1}+${var2}? I know this doesn't work.
9

The Advanced Bash Scripting Guide has the answer for you (http://tldp.org/LDP/abs/html/ivr.html). You have two options, the first is classic shell:

 #!/bin/bash

 server_list_all="server1 server2 server3";
 var1="server";
 var2="all";

 server_var="${var1}_list_${var2}"
 eval servers=\$$server_var;

 echo $servers

Alternatively you can use the bash shortcut ${!var}

 #!/bin/bash

 server_list_all="server1 server2 server3";
 var1="server";
 var2="all";

 server_var="${var1}_list_${var2}"
 echo ${!server_var}

Either approach works.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.