Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

easy way to cleanly dump contents of associative array in bash?

In zsh I can easily dump the contents of an associative array with a single command:

zsh% typeset -A foo
zsh% foo=(a 1 b 2)
zsh% typeset foo
foo=(a 1 b 2 )

However despite searching high and low, the best I could find was declare -p, whose output contains declare -A:

bash$ typeset -A foo
bash$ foo=([a]=1 [b]=2)
bash$ declare -p foo
declare -A foo='([a]="1" [b]="2" )'

Is there a clean way to obtain something like the zsh output (ideally foo=(a 1 b 2 ) or foo='([a]="1" [b]="2" )'), preferably without resorting to string manipulation?

like image 389
Adam Spiers Avatar asked Nov 04 '22 03:11

Adam Spiers


1 Answers

It seems there is no way to do this other than string manipulation. But at least we can avoid forking a sed process each time, e.g.:

dump_assoc_arrays () {
    for var in "$@"; do
        read debug < <(declare -p $var)
        echo "${debug#declare -A }"
    done
}
like image 118
Adam Spiers Avatar answered Nov 08 '22 05:11

Adam Spiers