Bash:附加到带有变量名称的列表

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

Bash: Append to list with variable name

bashshell

提问by user1837378

The first three commands work but the fourth does not. How can I append to an array with a variable in its name?

前三个命令有效,但第四个命令无效。如何附加到名称中带有变量的数组?

i=4
eval pim$i=
pim4+=(`date`)

pim$i+=(`date`)

Thanks!

谢谢!

回答by Charles Duffy

With bash 4.3, there's a feature targeted at just this use case: namerefs, accessed with declare -n. (If you have a modern ksh, they're also available using the namerefbuilt-in)

在 bash 4.3 中,有一个专门针对此用例的功能:namerefs,使用declare -n. (如果你有一个现代的ksh,它们也可以使用nameref内置的)

declare -n pim_cur="pim$i"
pim_cur+=( "$(date)" )

With bash 4.2, you can use printf -vto assign to array elements:

使用 bash 4.2,您可以使用printf -v分配给数组元素:

array_len=${#pim4[@]}
printf -v "pim4[$array_len]" %s "$(date)"

Prior to bash 4.2, you may need to use eval; this can be made safe by using printf %qto preprocess your data:

在 bash 4.2 之前,您可能需要使用 eval;这可以通过使用printf %q预处理您的数据来确保安全:

printf -v safe_date '%q' "$(date)"
eval "pim$i+=( $safe_date )" # only safe if you can guarantee $i to only contain
                             # characters valid inside a variable name (such as
                             # numbers)