Skip to content

Instantly share code, notes, and snippets.

@ormaaj
Last active November 3, 2022 05:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ormaaj/b843e4269483129bd7c7557c9af1cc38 to your computer and use it in GitHub Desktop.
Save ormaaj/b843e4269483129bd7c7557c9af1cc38 to your computer and use it in GitHub Desktop.
#!/bin/bash
typeset -gx BASH_COMPAT=51
shopt -u assoc_expand_once
function assignArray {
typeset -n ref=$1 || return
shift
[[ ${ref@a} == *A* && "! ($# % 2)" -ne 0 ]] || return
typeset -A map
typeset x
while ${2+\:} false; do
eval -- ${keymaps[$1]+"map=${keymaps[$1]}"}
map+=([${!ref}]=)
printf -v x '[%q]= ' "${!map[@]}"
typeset -gA keymaps+=([$1]="(${x% })")
ref+=([$1]=$2)
shift 2
done
}
function getArraysWithKey {
typeset -n ref=$1 || return
shift
[[ ${ref@a} == *A* ]] || return
eval -- ${keymaps[$1]+"ref=${keymaps[$1]}"}
}
typeset -A a b arrs
assignArray a k1 va1 k2 $'va2 * \n blah'
assignArray b k1 vb1 k2 vb2
assignArray a 'randomkey 1' va3
assignArray b 'randomkey 2 *' vb3
echo
getArraysWithKey arrs k1
printf 'arrays wirh %q: %s\n' k1 "${!arrs[*]}"
getArraysWithKey arrs 'randomkey 2 *'
printf 'arrays wirh %q: %s\n' 'randomkey 2 *' "${!arrs[*]}"
# typeset -p a b keymaps
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment