This came as a bit of a shock, but having a function export a variable declared as an array doesn’t actually export that variable. And if the variable already exists, it doesn’t change the value. It seems that passing by name is the only way to do that, but I have to experiment some more.
For the record, this does not work:
set -eux foo(){ declare -a FOO=(a b c) export FOO } echo "${#FOO}"
Nor does setting the already existing array to a new value inside a function.
This works, provided the version of Bash is new enough (note, not CentOS 7.x):
set -eux #note more than 3 values in the array before calling foo() declare -a FOO=(c d e f g) foo(){ local -n ARR="${1}" ARR=(a b c) } foo FOO echo "${#FOO[@]}" #note it will be 3 per foo()
updated: 2023-04-18 08:46:44
generated: 2024-05-03