Bash Return Multiple Values from a Function using an Associative Array: Difference between revisions
Jump to navigation
Jump to search
No edit summary |
|||
(5 intermediate revisions by the same user not shown) | |||
Line 4: | Line 4: | ||
=Overview= | =Overview= | ||
If the name of the associative array must be passed as the argument of the method, use [[#Option_1|Option 1]]. Otherwise, if we assume a known associative array set by the calling layer, [[#Option_2|Option 2]] is less complex. | |||
=<span id='Option_1'></span>Option 1 (Associative Array Name Passed as Argument)= | |||
==Invocation== | |||
<syntaxhighlight lang='bash'> | <syntaxhighlight lang='bash'> | ||
declare -A CONFIG | |||
load-config CONFIG | |||
echo ${CONFIG["SOMETHING"]} | |||
</syntaxhighlight> | |||
==Function Declaration== | |||
<syntaxhighlight lang='bash'> | |||
function load-config() { | |||
local map_var_name=$1 | |||
declare -A | grep -q "declare -A ${map_var_name}" || fail "no ${map_var_name} associative array declared" | |||
local key="SOMETHING" | |||
local value="BLAH" | |||
eval "${map_var_name}[\"${key}\"]=${value}" | |||
} | |||
</syntaxhighlight> | |||
=<span id='Option_2'></span>Option 2 (Associative Array is Set up by Calling Layer)= | |||
==Invocation== | |||
<syntaxhighlight lang='bash'> | |||
declare -A CONFIG | |||
load-config | |||
echo ${CONFIG["SOMETHING"]} | |||
</syntaxhighlight> | |||
==Function Declaration== | |||
<syntaxhighlight lang='bash'> | |||
function load-config() { | |||
declare -A | grep -q "declare -A CONFIG" || fail "no CONFIG associative array declared" | |||
local key="SOMETHING" | |||
local value="BLAH" | |||
CONFIG[${key}]=${value} | |||
} | |||
</syntaxhighlight> | </syntaxhighlight> |
Latest revision as of 21:17, 29 June 2021
Internal
Overview
If the name of the associative array must be passed as the argument of the method, use Option 1. Otherwise, if we assume a known associative array set by the calling layer, Option 2 is less complex.
Option 1 (Associative Array Name Passed as Argument)
Invocation
declare -A CONFIG
load-config CONFIG
echo ${CONFIG["SOMETHING"]}
Function Declaration
function load-config() {
local map_var_name=$1
declare -A | grep -q "declare -A ${map_var_name}" || fail "no ${map_var_name} associative array declared"
local key="SOMETHING"
local value="BLAH"
eval "${map_var_name}[\"${key}\"]=${value}"
}
Option 2 (Associative Array is Set up by Calling Layer)
Invocation
declare -A CONFIG
load-config
echo ${CONFIG["SOMETHING"]}
Function Declaration
function load-config() {
declare -A | grep -q "declare -A CONFIG" || fail "no CONFIG associative array declared"
local key="SOMETHING"
local value="BLAH"
CONFIG[${key}]=${value}
}