How to store (and load) a zsh String array to a file

arrayzsh

I want to store an array of some quotes (so basically real-world strings with new lines) in a file. How can I achieve it? I thought of setting the IFS to something like “xxxxxxxxx74765xxx” (which will never occur in my strings), but of course, IFS only works for single chars.

I can think of some ugly hacks to do it (e.g., store that nonsense string as a line between elements, read the file line by line and check each line against it, and rebuild the array thus.), but I will appreciate some more experienced opinions.

Best Answer

Just do:

typeset array > file

To load:

source file

(you can also use typeset -p array to also save the attributes of the array variable (exported, unique...)).

Alternatively:

print -rl -- ${(qq)array} > file

To load:

eval "array=($(<file))"

For your separator idea:

print -r -- ${(j[separator])array} > file

To load:

array=("${(@s[separator])"$(<file)"}")

(though beware it removes all trailing newline characters from the last element of the array and it doesn't work for an empty array).

Related Question