什么是间接扩张?${!var*} 是什么意思? [英] What is indirect expansion? What does ${!var*} mean?

查看:19
本文介绍了什么是间接扩张?${!var*} 是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读Bash 初学者指南".它说:

<块引用>

如果PARAMETER的第一个字符是感叹号,则Bash使用由PARAMETER的其余部分组成的变量的值作为变量名;这个变量然后被扩展,并且该值用于替换的其余部分,而不是 PARAMETER 本身的值.这称为间接扩展.

给出的例子是:

<块引用>

弗兰奇~>回声 ${!N*}NNTPPORT NNTPSERVER NPX_PLUGIN_PATH

这里我不太明白:

<块引用>

PARAMETER的其余部分构成的变量的值

由于 PARAMETER 只是 !N*,那么

<块引用>

其余的PARAMETER

就是 N*.这怎么可能形成一个变量?Bash 是否在那里搜索了所有可能的命令?

解决方案

如果你阅读了 bash 手册页,它基本上证实了你所说的:

<块引用>

如果参数的第一个字符是感叹号 (!),则引入了一个变量间接级别.Bash 使用由参数的其余部分形成的变量的值作为变量的名称;这个变量然后被扩展,并且该值用于替换的其余部分,而不是参数本身的值.这称为间接扩展.

但是,从那里继续阅读:

<块引用>

例外情况是下面描述的 ${!prefix*}${!name[@]} 的扩展.

${!prefix*} 匹配前缀的名称.扩展到名称以前缀开头的变量名称,以 IFS 特殊变量的第一个字符分隔.

换句话说,您的特定示例 ${!N*} 是您引用的规则的例外.但是,它确实在预期的情况下像广告中宣传的那样工作,例如:

$ export xyzzy=plugh ;出口插件=洞穴$ echo ${xyzzy} # 正常,xyzzy 到plugh插头$ echo ${!xyzzy} # 间接,xyzzy 到plugh 到cave洞穴

I'm reading "Bash Guide for Beginners". It says:

If the first character of PARAMETER is an exclamation point, Bash uses the value of the variable formed from the rest of PARAMETER as the name of the variable; this variable is then expanded and that value is used in the rest of the substitution, rather than the value of PARAMETER itself. This is known as indirect expansion.

The example given is:

franky ~> echo ${!N*}
NNTPPORT NNTPSERVER NPX_PLUGIN_PATH

I don't quite understand here:

the value of the variable formed from the rest of PARAMETER

As the PARAMETER is just !N*, then

the rest of PARAMETER

is just N*. How could this form a variable? Did Bash search all possible command there?

解决方案

If you read the bash man page, it basically confirms what you have stated:

If the first character of parameter is an exclamation point (!), a level of variable indirection is introduced. Bash uses the value of the variable formed from the rest of parameter as the name of the variable; this variable is then expanded and that value is used in the rest of the substitution, rather than the value of parameter itself. This is known as indirect expansion.

However, reading on from there:

The exceptions to this are the expansions of ${!prefix*} and ${!name[@]} described below.

${!prefix*} Names matching prefix. Expands to the names of variables whose names begin with prefix, separated by the first character of the IFS special variable.

In other words, your particular example ${!N*} is an exception to the rule you quoted. It does, however, work as advertised in the expected cases, such as:

$ export xyzzy=plugh ; export plugh=cave

$ echo ${xyzzy}  # normal, xyzzy to plugh
plugh

$ echo ${!xyzzy} # indirection, xyzzy to plugh to cave
cave

这篇关于什么是间接扩张?${!var*} 是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆