I am creating a function were the first argument would be used as a global variable that holds an array of numbers populated by the rest of the argument but i get a syntax error while assigning the values, but if i just assign a scalar to the variable it works. This is the code below
the value of new_set_name
which is a
would hold all the array elements
#!/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[@]}
am a bit surprised to see it work for scalars and errors are spit out for arrays. How can i solve this ?
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 Bash FAQ #6 for more information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With