Error reading multiline string in array?

I use the following bash codes to read a multi-line string in an array. I want each element of the array to correspond to one row of the string.

mytext="line one
line two
line three"
IFS=$'\n' read -a lines <<<"${mytext}"
echo "len=${#lines[@]}"
for line in "${lines[@]}"
do
   echo "[$line]"
done

I expect len ​​to be 3, and the lines array to be properly initialized. However, I got the following result:

len=1
[line one]

Did I use the wrong "IFS"? What are the errors in bash code? Thanks in advance.

+4
source share
3 answers

, , read , , , IFS , . , read, . :

lines=()
while read; do
  lines+=("$REPLY")
done <<< "$mytext"

- :

IFS='+' read -a lines <<< "${mytext//$'\n'/+}"
$ IFS=@
$ echo "${lines[*]}"
line one@line two@line three

mapfile (a.k.a. readarray) , , Bash 4:

mapfile -t lines <<< "$mytext"

$ printf '[%s]\n' "${lines[@]}"
[line one]
[line two]
[line three]

-t mapfile .

+6

while :

arr=()
while read -r line; do
   arr+=("$line")
done <<< "$mytext"

set | grep arr
arr=([0]="line one" [1]="line two" [2]="line three")
+1

Not sure what is wrong in your case, but here is a workaround:

a=0
while read lines[$a]; do
    ((a++))
done <<< "${mytext}"
unset lines[$a]; #last iteration has already failed. Unset that index.
+1
source

Source: https://habr.com/ru/post/1529212/


All Articles