Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

syntax error while working with array

Tags:

bash

shell

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 ?

like image 636
0.sh Avatar asked Oct 18 '22 00:10

0.sh


1 Answers

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.

like image 195
PesaThe Avatar answered Oct 23 '22 01:10

PesaThe