Array syntax error

I create a function because the first argument will be used as a global variable containing an array of numbers populated by the rest of the argument, but I get a syntax error when assigning values, but if I just assign a scalar to a variable it works. This is the code below

value new_set_name , which a will contain all elements of the array

 #!/usr/bin/env bash create() { local new_set_name=${1} shift; declare -g ${new_set_name}=( ${@} ); echo ${!new_set_name} } create a 1 2 3 4 echo ${a[@]} 

but if I tried it with a scalar, it works

 #!/usr/bin/env bash create() { local new_set_name=${1} shift; declare -g ${new_set_name}=1; echo ${!new_set_name} } create a 1 2 3 4 echo ${a[@]} 

I'm a little surprised to see that it works for scalars, and errors spit out for arrays. How can i solve this?

+5
source share
1 answer

In bash 4.3 or later, you can use nameref :

 #!/usr/bin/env bash create() { local -n name=$1; shift name=(" $@ ") } create a 1 2 3 4 printf '%s\n' "${a[@]}" 
 1 2 3 4 

See the Bash FAQ # 6 for more details.

+3
source

Source: https://habr.com/ru/post/1274557/


All Articles