Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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:

(
[james]=bond
)

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:

#!/bin/bash
file=`cat $1`
key=$2
value=$3
declare -A row="$file"
row[$key]=$value
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

Giving

(
[james]=bond
[honey]=rider
)

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

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

1 Answer 1

up vote 5 down vote accepted

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
  row[$1]=$2
  shift 2
done
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[@]}"
do
  echo "key  : $i"
  echo "value: ${row[$i]}"
done
share|improve this answer
    
Hooray for self-qualifying parameters! But would a more specific error string not be more useful? –  mikeserv Jun 10 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 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 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 at 14:45

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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