Bash, Concatenating 2 strings to reference a 3rd variable Bash, Concatenating 2 strings to reference a 3rd variable bash bash

Bash, Concatenating 2 strings to reference a 3rd variable


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=servervar2=allcombined=${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"


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.