help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: fastest way to copy a bash array to a file


From: Greg Wooledge
Subject: Re: fastest way to copy a bash array to a file
Date: Thu, 13 Jul 2023 06:58:24 -0400

On Thu, Jul 13, 2023 at 10:14:31AM +0700, Budi wrote:
> How fastest, simplest way to copy or write a bash array values to a file e.g.
> 
> m=( foo bar baz )
> 
> printf '%s\n' "${m[@]}" >test

What matters is what you plan to *do* with the file after you've written
it.  Why are you writing the array to a file?  Who's going to read the
file?  What kind of data do you have in your array?

What you've shown here won't work if your array elements might contain
newline characters.  On the other hand, if you *know* they will never
contain newline characters, this is a perfectly good solution.

If the array is going to be read back in by bash, under the same name as
you're using right now, then you might just dump "declare -p m" to the
file, and source the file to restore the array later.

If the array elements contain arbitrary data (possibly including newlines),
and if the previous paragraph does not apply for any reason, then the
preferred serialization format is to use NUL bytes instead of newlines
after each element.

    printf '%s\0' "${m[@]}" > myfile

Bash 4.4 and above can read that back in with readarray -d ''.  With
older bash versions, you would need a while IFS= read -r -d '' loop.

If the array data are going to be read by some other program that's not
bash, then you would want to tailor your serialization format to the
reader's needs.  Without knowing the reader, it's impossible to pick
a solution.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]