Easy way to clear contents of associative array in bash?

In zsh I can easily flush 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 get something like zsh output (ideally foo=(a 1 b 2 ) or foo='([a]="1" [b]="2" )' ), preferably without resorting to string manipulation?

+4
source share
2 answers

There seems to be no way to do this other than string manipulations. But at least we can avoid forking the sed process every time, for example:

 dump_assoc_arrays () { for var in " $@ "; do read debug < <(declare -p $var) echo "${debug#declare -A }" done } 
+2
source

declare -A is redundant

Good sir, declare -A not redundant.

 $ foo=([a]="1" [b]="2") $ echo ${foo[a]} 2 $ declare -A bar=([a]="1" [b]="2") $ echo ${bar[a]} 1 
0
source

All Articles