从Bash函数返回字典 [英] Returning a Dictionary from a Bash Function

查看:46
本文介绍了从Bash函数返回字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在bash中使用一个函数,该函数将Dictionary创建为局部变量.用一个元素填充字典,然后将该字典作为输出返回.

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.

以下代码正确吗?

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

如何访问上面函数的输出?我可以在bash中使用以下命令吗?

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

The_Output_Dictionary=Dictionary_Builder()

推荐答案

要捕获命令或函数的输出,请使用命令替换:

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

The_Output_Dictionary=$(Dictionary_Builder)

并输出要返回的值,即用 echo 替换 return .不过,您不能轻易地返回一个结构,但是您可以尝试返回一个声明该结构的字符串(见下文).

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).

该函数中无需使用 local unset . declare 会在函数内部创建局部变量,除非 -g 另有说明.新创建的变量始终为空.

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)

换句话说

#!/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

这篇关于从Bash函数返回字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆