Bash Return Multiple Values from a Function using an Associative Array: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
No edit summary
 
Line 3: Line 3:
* [[Bash_Functions#Function_Patterns|Bash Functions | Function Patterns]]
* [[Bash_Functions#Function_Patterns|Bash Functions | Function Patterns]]


=Invocation=
=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
declare -A CONFIG
Line 9: Line 13:
echo ${CONFIG["SOMETHING"]}
echo ${CONFIG["SOMETHING"]}
</syntaxhighlight>
</syntaxhighlight>
 
==Function Declaration==
=Function Declaration=
<syntaxhighlight lang='bash'>
<syntaxhighlight lang='bash'>
function load-config() {
function load-config() {
Line 18: Line 21:
   local value="BLAH"
   local value="BLAH"
   eval "${map_var_name}[\"${key}\"]=${value}"
   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}
}