Just to have a complete and runnable example.
One function creates a global associative array variable inside itself.
Other function assigns a value to the array variable.
bash 4.2 and above
set -euf +x -o pipefail # There is no place for implicit errors in this script.
function init_arrays(){
# FYI. Multiple array declarations are not a problem. You can invoke it multiple times.
# The "-gA" switch is the trick for the global array declaration inside a function.
declare -gA my_var
}
function do_work(){
init_arrays
my_var[$1]=OPPA
}
do_work some_key
echo ${my_var[some_key]}
echo It is expected to get OPPA value printed above
Tested over GNU bash, version 4.4...
macOS
bash on macOS has 3.2 version (02/2023).
You have to use zsh, if you remove comments from the above init_arrays function.
function init_arrays(){
declare -gA my_var
}
function do_work(){
init_arrays
my_var[$1]=OPPA
}
do_work some_key; echo ${my_var[some_key]}
Important notes
(bash) The declare -A
command doesn't actually create an associative array immediately; it just sets an attribute on a variable name which allows you to assign to the name as an associative array. The array itself doesn't exist until the first assignment (!!!).
PKGBUILD
s need associative arrays to be global to be readable insidepackage_pkgname
functions.