引用名称包含点的 bash 变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26506539/
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 11:37:07  来源:igfitidea点击:

Reference to a bash variable whose name contains dot

bash

提问by Taher Khorshidi

I have a bash variable: agent1.ipwith 192.168.100.137as its value. When I refer to it in echolike this:

我有一个 bash 变量:agent1.ipwith192.168.100.137作为它的值。当我echo像这样提到它时:

echo $agent1.ip

the result is:

结果是:

.ip

How can I access the value?

如何访问该值?

UPDATE:my variables are:

更新:我的变量是:

enter image description here

在此处输入图片说明

回答by John Zwinck

Bash itself doesn't understand variable names with dots in them, but that doesn't mean you can't have such a variable in your environment. Here's an example of how to set it and get it all in one:

Bash 本身不理解带有点的变量名,但这并不意味着您的环境中不能有这样的变量。这是一个如何设置并将其全部整合的示例:

env 'agent1.ip=192.168.100.137' bash -c 'env | grep ^agent1\.ip= | cut -d= -f2-'

回答by chepner

Since bash.ipis not a valid identifier in bash, the environment string bash.ip=192.168.100.37is not used to create a shell variable on shell startup.

由于bash.ip不是 中的有效标识符bash,环境字符串bash.ip=192.168.100.37不用于在 shell 启动时创建 shell 变量。

I would use awk, a standard tool, to extract the value from the environment.

我会使用awk标准工具 来从环境中提取价值。

bash_ip=$(awk 'BEGIN {print ENVIRON["bash.ip"]}')

回答by nikolay

The cleanest solution is:

最干净的解决方案是:

echo path.data | awk '{print ENVIRON[]}'

回答by SMA

Try this:

尝试这个:

export myval=`env | grep agent1.port | awk -F'=' '{print }'`;echo $myval

回答by shellter

Is your code nested, and using functions or scripts that use ksh?

您的代码是否嵌套并使用了使用 ksh 的函数或脚本?

Dotted variable names are an advanced feature in ksh93. A simple case is

带点的变量名是 ksh93 中的一项高级功能。一个简单的案例是

$ a=1
$ a.b=123
$ echo ${a.b}
123
$ echo $a
1

If you first attempt to assign to a.b, you'll get

如果您第一次尝试分配给a.b,您将获得

 -ksh: a.b=123: no parent

IHTH

IHTH