Bash, Concatenating 2 strings to reference a 3rd variable

21,563

Solution 1

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"

Solution 2

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.

Share:
21,563
Im Fine
Author by

Im Fine

Updated on June 12, 2020

Comments

  • Im Fine
    Im Fine almost 4 years

    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

  • Im Fine
    Im Fine almost 12 years
    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!
  • Timothy Swan
    Timothy Swan over 6 years
    So is there really no way to do this without creating a new variable?
  • Eric Smith
    Eric Smith over 6 years
    @TimothySwan, eval "echo `echo \\$\\{${var1}_list_${var2}\}`" but that's just nasty.
  • Ungeheuer
    Ungeheuer over 6 years
    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.