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!
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!
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 nameref
built-in)
declare -n pim_cur="pim$i"
pim_cur+=( "$(date)" )
With bash 4.2, you can use printf -v
to assign to array elements:
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 %q
to preprocess your data:
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)