user1333872
user1333872

Reputation:

BASH copy of array

I am new to BASH.

I have string with name ARRAY, but i need set ARRAY as array, and this ARRAY as array must include parts of string from ARRAY as string separated by \n (new line)

This is what I have:

ARRAY=$'one\ntwo';
x=$ARRAY;
IFS=$'\n' read -rd '' -a y <<<"$x";
y=(${x//$'\n'/});
IFS=$'\n' y=(${x//$'\n'/ });
IFS=$'\n' y=($x);
unset ARRAY; (i try unset ARRAY)
ARRAY=$y; (this not works correctrly)
echo ${ARRAY[1]}; //result ARRAY[0]="one",ARRAY[1]=""

But if I try echo ${y[1]}; //all is right y[0]="one" y[1]="two"

My problem is that I cannot set ARRAY as copy of y array..

Upvotes: 1

Views: 1410

Answers (1)

gniourf_gniourf
gniourf_gniourf

Reputation: 46843

The way you're splitting the string at the newlines is correct:

array=$'one\ntwo'
IFS=$'\n' read -rd '' -a y <<<"$array"

Now, why do you give a different name, if eventually you want the variable array to contain the array? just do:

IFS=$'\n' read -rd '' -a array <<<"$array"

There are no problems if array appears both times here.


Now, if you want to copy an array, you'll do this (assuming the array to copy is called y as in your example):

array=( "${y[@]}" )

Note, that this will not preserve the sparseness of the array (but in your case, y is not sparse so there are no problems with this).


Another comment: when you do IFS=$'\n' read -rd '' -a y <<<"$array", read will return with a return code of 1; while this is not a problem, you may still want to make return happy by using:

IFS=$'\n' read -rd '' -a array < <(printf '%s\0' "$array")

A last comment: instead of using read you can use the builtin mapfile (bash≥4.0 only):

mapfile -t array <<< "$array"

Upvotes: 2

Related Questions