linux – Bash,按值引用数组?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了linux – Bash,按值引用数组?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1684字,纯文字阅读大概需要3分钟。
内容图文
有没有办法通过引用值来访问变量?
BAR=("hello", "world")
function foo() {
DO SOME MAGIC WITH $1
// Output the value of the array $BAR
}
foo "BAR"
解决方法:
也许您正在寻找的是间接扩张.来自man bash:
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. The
exceptions to this are the expansions of ${!prefix*} and ${!name[@]} described below. The exclamation point must immediately fol‐
low the left brace in order to introduce indirection.
相关文档:Shell parameter expansion (Bash Manual)和Evaluating indirect/reference variables (BashFAQ).
这是一个例子.
$MYVAR="hello world"
$VARNAME="MYVAR"
$echo ${!VARNAME}
hello world
请注意,数组的间接扩展有点麻烦(因为${!name [@]}表示其他内容.请参阅上面的链接文档):
$BAR=("hello" "world")
$v="BAR[@]"
$echo ${!v}
hello world
$v="BAR[0]"
$echo ${!v}
hello
$v="BAR[1]"
$echo ${!v}
world
把它放在你的问题的上下文中:
BAR=("hello" "world")
function foo() {
ARR="${1}[@]"
echo ${!ARR}
}
foo "BAR" # prints out "hello world"
注意事项:
>数组语法的间接扩展在旧版本的bash(pre v3)中不起作用.见BashFAQ article.
>看来您无法使用它来检索数组大小. ARR =“#${1} [@]”无效.但是,如果数组的副本不是非常大,您可以通过复制数组来解决此问题.例如:
function foo() {
ORI_ARRNAME="${1}[@]"
local -a ARR=(${!ORI_ARRNAME}) # make a local copy of the array
# you can now use $ARR as the array
echo ${#ARR[@]} # get size
echo ${ARR[1]} # print 2nd element
}
内容总结
以上是互联网集市为您收集整理的linux – Bash,按值引用数组?全部内容,希望文章能够帮你解决linux – Bash,按值引用数组?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。