User Tools

Site Tools


dev:shellscripts:juntando_duas_variaveis_formar_terceira_variavel_em_shellscript

juntando ou concatenando duas variáveis para formar uma terceira variável em shellscript

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}

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”

dev/shellscripts/juntando_duas_variaveis_formar_terceira_variavel_em_shellscript.txt · Last modified: 2022/11/04 00:34 by 127.0.0.1