Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a Dictionary from a Bash Function

I want to have a function in bash, which create a Dictionary as a local variable. Fill the Dictionary with one element and then return this dictionary as output.

Is the following code correct?

function Dictionary_Builder ()
{
local  The_Dictionary
unset  The_Dictionary
declare -A The_Dictionary
The_Dictionary+=(["A_Key"]="A_Word")
return $The_Dictionary
}

How can I access to the output of the function above? Can I use the following command in bash?

The_Output_Dictionary=Dictionary_Builder()
like image 972
Admia Avatar asked Jul 24 '26 14:07

Admia


1 Answers

To capture output of a command or function, use command substitution:

The_Output_Dictionary=$(Dictionary_Builder)

and output the value to return, i.e. replace return with echo. You can't easily return a structure, though, but you might try returning a string that declares it (see below).

There's no need to use local and unset in the function. declare creates a local variable inside a function unless told otherwise by -g. The newly created variable is always empty.

To add a single element to an empty variable, you can assign it directly, no + is needed:

The_Dictionary=([A_Key]=A_Word)

In other words

#!/bin/bash
Dictionary_Builder () {
    declare -A The_Dictionary=([A_Key]=A_Word)
    echo "([${!The_Dictionary[@]}]=${The_Dictionary[@]})"
}

declare -A The_Output_Dictionary="$(Dictionary_Builder)"
echo key: ${!The_Output_Dictionary[@]}
echo value: ${The_Output_Dictionary[@]}

For multiple keys and values, you need to loop over the dictionary:

Dictionary_Builder () {
    declare -A The_Dictionary=([A_Key]=A_Word
                               [Second]=Third)
    echo '('
    for key in  "${!The_Dictionary[@]}" ; do
        echo "[$key]=${The_Dictionary[$key]}"
    done
    echo ')'
}

declare -A The_Output_Dictionary="$(Dictionary_Builder)"
for key in  "${!The_Output_Dictionary[@]}" ; do
    echo key: $key, value: ${The_Output_Dictionary[$key]}
done
like image 101
choroba Avatar answered Jul 27 '26 07:07

choroba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!