Skip to content

Instantly share code, notes, and snippets.

@ormaaj
Last active August 26, 2024 18:08
Show Gist options
  • Save ormaaj/70a88daedf65aeb8464a9c27f7187a1e to your computer and use it in GitHub Desktop.
Save ormaaj/70a88daedf65aeb8464a9c27f7187a1e to your computer and use it in GitHub Desktop.
multiple mixed type array to set
#!/usr/bin/env bash
BASH_COMPAT=51
# Swap or merge keys and indices
function arr2set {
typeset -i n m
typeset -n _ret=$1 r
[[ ${_ret@a} == *A* ]] || return
shift
for r do
set -- "${!r[@]}"
case ${r@a} in
*a*) (( m = $# ))
while
(( _ret[\${r[\${1}]}] = (n + (m - $#)) ))
${1+\:} break
shift
do :
done
((n += m))
;;
*A*) eval "_ret+=(${| printf -v REPLY '[%q]=%q ' "${r[@]@k}"; } )"
esac
done
}
function m {
typeset -a a=({a..c}) b=({d..f})
typeset -A s c=([muh]=mu [moo]=muu)
arr2set s a b c
typeset -p s
}
m
# declare -A s=([moo]="muu" [f]="5" [e]="4" [d]="6" [c]="2" [b]="1" [a]="3" [muh]="mu" )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment