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

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
(Created page with "=Internal= * Bash Arrays | Associative Array Patterns * Bash_Functions#Function_Patterns|Bash Functions | Function Patte...")
 
No edit summary
 
(6 intermediate revisions by the same user not shown)
Line 2: Line 2:
* [[Bash_Arrays#Associative_Array_Patterns|Bash Arrays | Associative Array Patterns]]
* [[Bash_Arrays#Associative_Array_Patterns|Bash Arrays | Associative Array Patterns]]
* [[Bash_Functions#Function_Patterns|Bash Functions | Function Patterns]]
* [[Bash_Functions#Function_Patterns|Bash Functions | Function Patterns]]
=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'>
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>

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}
}