3

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.

6

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).

1

The two portable (ksh, zsh, bash) solutions AFAICT are:

 typeset -p arr >./file              # save array
 . ./file                            # read array

And

printf '%q\n' "${arr[@]}" >./file    # save array
eval "arr=( $(< ./file) )"           # read array

Note that the first solution will create a local variable if used inside a function in bash.

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.