0

So in order to be versatile, I make a lot of functions and i want to define my own variable name when i call on that function. For basic text, numbers it works and this is how I do it

function func_get_device_hostname
{
    local _device_hostname=$1
    local device_hostname2="TEST"
    eval $_device_hostname="'$device_hostname2'"
}

function func_display_device_hostname
{
    func_get_device_hostname device_hostname
    echo $device_hostname
}

but when i use that same method with an array like so

function func_get_vds_ip
{
    func_get_vds_count vds_count
    local _arr_vds_ip=$1
    arr_vds_ip2=()
    i=1
    while [ $i -le $vds_count ]; do
        local arr_vds_ip2+=($(avahi-browse -rvpc vds._tcp | grep "=;" | cut -d ';' -f8 | sed -n $i' p'))
        i=$(($i+1))
    done
    echo ""
    eval $_arr_vds_ip="'$arr_vds_ip2'"
}

function func_display_vds_ip
{
    func_get_vds_ip arr_vds_ip
    echo -n "VDS IP        "
    for i in "${arr_vds_ip[@]}"
    do
        echo -n "$i"
        echo -n " - "
    done
}

I get the following error

line 339: {arr_vds_ip[@]}=192.168.18.82: command not found

line 339 refers to this part of the code

    eval $_arr_vds_ip="'$arr_vds_ip2'"

what is the best method to do this? am i using a wrong command?

1 Answer 1

0

You could be using namerefs (See Shell Parameters and search down for "nameref"). Once you declare a nameref, you just use the local variable like a normal variable, and the contents are reflected in the referenced variable.

For the simple case:

function func_get_device_hostname {
    local -n _device_hostname=$1
    local name=TEST
    _device_hostname=$name
}

testing

$ declare -p foo
bash: declare: foo: not found
$ func_get_device_hostname foo
$ declare -p foo
declare -- foo="TEST"

For the array case:

function func_get_vds_ip {
    local -n _arrname=$1
    local count=10 i
    _arrname=()
    for ((i=1; i<=count; i++)); do
        _arrname+=($RANDOM)
    done
}

testing

$ declare -p bar
bash: declare: bar: not found
$ func_get_vds_ip bar
$ declare -p bar
declare -a bar=([0]="23299" [1]="13876" [2]="24702" [3]="17413" [4]="14999" [5]="16309" [6]="25625" [7]="29001" [8]="7117" [9]="23532")

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.