I'm trying to write a function that redirects the contents of an
array to a file. The array contains the lines of a data file with
white space.
The function seems to preserve all white space when redirected
except that it seems to ignore newlines. As a consequence, the
elements of the array are appended one after the other.
NOTES:
Adding local IFS=$'\n' to the beginning of the function doesn't
seem to make any difference. I also tried printf in place of
echo but was not fully tested.
You could try with echo -e to have the newline recognized. Though it would be ok to see how you assign/fill this array. Anyway here is a general example:
$> array=( a b "c\n" d e )
$> echo -e ${array[@]}
a b c
d e
$> echo -e ${array[0]}
a
$> echo -e ${array[1]}
b
$> echo -e ${array[2]}
c
$> echo -e ${array[3]}
d
$> echo -e ${array[4]}
e
It's a solution that's a combination of several posts from
the forum, the majority of which was suggested by a forum
member to another problem I had with arrays and I've used
the same general format and extended it to other functions.
After experimenting with other methods, it was the only
one that worked and the most elegant. After the array is
loaded, I have no further problems using or manipulating it.
use: array_load ARRAY $PATHTOFILE
function array_load
{
local IFS=$'\n'
eval "$1=( \$( < \"$2\" ) )"
}
The 'array_load' function populates the array with each
element within quotes. The 'array_save' function above,
outputs each element serially on one line.
However, I did manage a solution that works:
use: save_array ARRAY $filename
function array_assign
{
eval "$1=( \"\${$2[@]}\" )"
}
function array_save
{
local -a ARRAY; array_assign ARRAY $1
local FILE; FILE=$2
for ELEMENT in "${ARRAY[@]}"; do
echo $ELEMENT
done > $FILE
}
But it's not as elegant as the other functions. As the
function is part of a library that forms the foundation
of re-useable code concept, ideally it would have
been independent and used no named variables.
After weeks of searching the net and examining tens of
solutions, I do believe that the entire approach to arrays
in bash has been redefined due to your expertise and opened
up new possibilities for myself and other users. Dare I say
that it's even worthy of a third book!
I nearly had the solution myself, but used double quotes
around "string newline" instead of single quotes, should have
known better. Thanks also goes to nDuff at #bash for his/her
suggestions for using printf.