I want to memorize an associative array between different script runs. What I have so far is that given a text file containing one key/value pair:


Is a script to load that into an associative array, add to it, then echo it out in a way which can be redirected into a second file:

file=`cat $1`
declare -A row="$file"
echo "("
for server in "${!row[@]}"
    do echo "[$server]=${row[$server]}"; done
echo ")"

then I can run it as:

./arrays.sh file1 honey rider > file2 ; mv file2 file1



Yet it seems very clunky. Is there a cleaner way to do this?

  • 4
    declare -p hash > file to save the hash associative array. source file to restore. – Stéphane Chazelas Jun 10 '14 at 13:01
  • 2
    It should probably be arrays.bash... – mikeserv Jun 10 '14 at 14:37

In bash, declare -p can be used to dump the definition of a variable as shell code ready to be interpreted, so you can do updates to the file with:

#! /bin/bash -
file=${1?}; shift
declare -A row
source -- "$file" || exit
while [ "$#" -ge 2 ]; do
  shift 2
declare -p row > "$file"

A script to show the contents of the file would be:

#! /bin/bash -
file=${1?}; shift
declare -A row
source -- "$file"
for i in "${!row[@]}"
  echo "key  : $i"
  echo "value: ${row[$i]}"
  • Hooray for self-qualifying parameters! But would a more specific error string not be more useful? – mikeserv Jun 10 '14 at 14:16
  • @mikeserv, sure, but that's beyond the point of the answer. By all means, please do add proper syntax checking as appropriate. One may also want to check that there be an even number of arguments after the file name (or use the odd single argument as a means to remove a single element). – Stéphane Chazelas Jun 10 '14 at 14:19
  • I dunno... Maybe don't ask me to edit... You're not supposed to invite the vampires in... But what's done is done, I guess. – mikeserv Jun 10 '14 at 14:22
  • oh, sorry. I guess I shouldn't have taken that literally? I did do as you asked though and made it a little more robust without complicating it. – mikeserv Jun 10 '14 at 14:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.