Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: read/write associative array from/to file



Hi Thomas,

2012/1/3 Thomas Gstädtner <thomas@xxxxxxxxxxxxxx>:
> I want to read and write an associative array from/to a file, i.e. a
> very simple key-value database. Is this possible; if so, how?
> If not, what would be the most practical solution to work with a file
> like this?
> ---
> key1 value1
> key2 value2
> key3 value3
> ...

If 1) you're confident about the content of your database (ie. nobody
can write nasty things in it) and 2) you do not plan to have a lot of
entries in your database and 3) concurrency and performance is not an
issue, an easy solution is to serialize your array in a shell script
and to source this script to reload the database:

# dummy associative array
typeset -A myArray
myArray=(
  foo 1
  bar 42
)

# serialization
echo "myArray=(${(kv)myArray})" >| $db

# loading (don't forget to typeset -A myArray before this)
source $db

Best regards,

-- 
Jérémie



Messages sorted by: Reverse Date, Date, Thread, Author