Bash Return Multiple Values from a Function using an Associative Array

From NovaOrdis Knowledge Base
Revision as of 21:17, 29 June 2021 by Ovidiu (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

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