5

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 ?

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

5 Comments

just the answer am looking for thanks, but it seems like there is no documentation for nameref , when i do help -m local , the -n switch was not specified
@0.sh There is a link in the answer. Click on nameref.
@0.sh Also, make sure to check out the updated link. And use help declare instead of help local.
oh, i thought local , declare, typeset do the same thing ?
@0.sh The thing is, the help for local just says OPTION can be any option accepted by 'declare'. So to see the options, -n for example, you need to use help declare.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.