1

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

2
  • Please add your desired result to your question. Commented Feb 13, 2016 at 8:30
  • ARRAY[0]="one" ARRAY[1]="two" Commented Feb 13, 2016 at 8:45

1 Answer 1

2

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"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.