1

In bash 4.3 script, I have variables:

environment="local"
config_local=("a" "b" "b" "d")
copy_from="config_${environment}"

I want to copy values from array with name stored in copy_from to another array named config.

I tried this and some variations:

config=${!copy_from}
echo "${config[@]}"
config=${!copy_from[@]}
echo "${config[@]}"
config=("${!copy_from}")
echo "${config[@]}"
config=("${!copy_from[@]}")
echo "${config[@]}"

but I can't copy whole array to config and get only 0 or first element only:

a
0
a
0

How can I do it in bash?

3

There are ways to do this with eval, but they are insecure. There are some ways to do this with on bash 2.05b+:

$ foo=(a b c)
$ name=foo
$ temp_indirect=${name}[@]
$ printf '<%s>\n' "${!temp_indirect}"
<a>
<b>
<c>

This is pretty ugly because it relies on (potentially undocumented?) implementation details of the bash parser, so use it at your own risk.

In general, if you want complex data structures, I'd suggest another language. In many cases there are workarounds to make them possible in bash, but the syntax is abstruse because the language is not optimised for them (it is mostly optimised for IPC and manipulation of files).

  • What are you talking about, everything in this answer is documented/defined behaviour? – 123 Apr 29 '16 at 13:42
  • @123 I would be interested to know where you find the behaviour of stringifying ${name}[@] and then using indirection to be defined behaviour. As far as I know, indirection containing array indices is not defined and is merely a implementation detail of the parser. – Chris Down Apr 29 '16 at 14:08
  • What do you mean, why would using it with an array be any different? It just expands the variable and then shows the contents of the expanded string. An array is still a variable. – 123 Apr 29 '16 at 14:13
  • @123 Because [@] is not part of a variable name, so it relies on the sequence the parser uses internally to perform indirection. The fact that it works is more a historic coincidence rather than intentional. – Chris Down Apr 30 '16 at 21:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.