Bash – Reading stdin into a bash array

arraybashread

I want to accomplish the equivalent of:

list=()
while read i; do
  list+=("$i")
done <<<"$input"

with

IFS=$'\n' read -r -a list <<<"$input"

What am I doing wrong?

input=`/bin/ls /`

IFS=$'\n' read -r -a list <<<"$input"

for i in "${list[@]}"; do
  echo "$i"
done

This should print a listing of /, but I'm only getting the first item.

Best Answer

You must use mapfile (or its synonym readarray, which was introduced in bash 4.0):

mapfile -t list <<<"$input"

One read invocation only work with one line, not the entire standard input.

read -a list populate the content of first line of standard in to the array list. In your case, you got bin as the only element in array `list.

Related Question