动态参数扩展 [英] Dynamic parameter expansion

查看:57
本文介绍了动态参数扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Bash中可以动态显示parameter expansion吗?

$ TEST_1=12345
$ TEST_2=54321
$ for i in 1 2; do echo ${TEST_$i}; done
-bash: ${TEST_$i}: bad substitution
$ echo ${!TEST_*}
TEST_1 TEST_2

所需的输出:

$ for i in 1 2; do echo ${TEST_$i}; done
12345
54321

推荐答案

您可以使用间接参数扩展(请参见man bash):

You can use indirect parameter expansion (see man bash):

If the first character of parameter is an  exclamation  point  (!),  it
introduces a level of variable indirection.  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 exceptions to this are the expansions
of ${!prefix*} and ${!name[@]} described below.  The exclamation  point
must  immediately  follow the left brace in order to introduce indirec-
tion.

也就是说:

for i in 1 2; do var="TEST_$i"; echo "${!var}"; done

测试:

$ TEST_1=12345
$ TEST_2=54321 
$ for i in 1 2; do var="TEST_$i"; echo "${!var}"; done
12345
54321

这篇关于动态参数扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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