Bash,连接 2 个字符串以引用第三个变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10990436/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 02:28:26  来源:igfitidea点击:

Bash, Concatenating 2 strings to reference a 3rd variable

stringbashvariablesconcatenation

提问by Im Fine

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

我有一个 bash 脚本,我在连接 2 个变量以调用第 3 个变量时遇到了一些问题。

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

编辑:清理了一下

回答by Eric Smith

The Bash Reference Manual explains how you can use a neat feature of parameter expansionto 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 combinedmeans "use the variable whose name is defined by the contents of combined"

引用时的感叹号combined表示“使用名称由“的内容定义的变量combined

回答by Recurse

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:

Advanced Bash Scripting Guide 为您提供了答案 (http://tldp.org/LDP/abs/html/ivr.html)。您有两个选择,第一个是经典 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}

或者,您可以使用 bash 快捷方式 ${!var}

 #!/bin/bash

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

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

Either approach works.

这两种方法都有效。