arraysbashassociative-arraydata-retrievalstoring-information

Storing Bash associative arrays


I want to store (and retrieve, of course) Bash's associative arrays and am looking for a simple way to do that.

I know that it is possible to do it using a look over all keys:

for key in "${!arr[@]}"
do
  echo "$key ${arr[$key]}"
done

Retrieving it could also be done in a loop:

declare -A arr
while read key value
do
  arr[$key]=$value
done < store

But I also see that set will print a version of the array in this style:

arr=([key1]="value1" [key2]="value2" )

(Unfortunately along with all other shell variables.)

Is there a simpler way for storing and retrieving an associative array than my proposed loop?


Solution

  • To save to a file:

    declare -p arr > saved.sh
    

    (You can also use typeset instead of declare if you prefer.)

    To load from the file:

    source saved.sh