1

I have a sample input file called in with the following contents:

m@m-X555LJ:~/wtfdir$ cat in
asdf1 jkl1
asdf2 jkl2
asdf3 jkl3

I now execute:

m@m-X555LJ:~/wtfdir$ mapfile < ./in

As expected, the variable MAPFILE is now an array that breaks the file in into lines:

m@m-X555LJ:~/wtfdir$ echo ${MAPFILE[0]}
asdf1 jkl1
m@m-X555LJ:~/wtfdir$ echo ${MAPFILE[1]}
asdf2 jkl2

So now I want to break the first line into words. AFAIK read -a arrname reads a line from standard input, breaks it into words and stores the result in an array called arrname. So I type:

m@m-X555LJ:~/wtfdir$ echo ${MAPFILE[0]} | read -a words

In my mental model, this is what should happen: echo ${MAPFILE[0]} echoes the first row of MAPFILE (that is, asdf1 jkl1) into standard output, but this is piped into standard input of read -a words, so read should read this line and split it into words and store the result in an array called words.

Yet sadly, this doesn't happen:

m@m-X555LJ:~/wtfdir$ echo ${words[0]}

m@m-X555LJ:~/wtfdir$

Yep. echo ${words[0]} prints nothing, while I was hoping it would print asdf1.

Why does it happen? And where is my mistake? And how to make it work?

marked as duplicate by Kusalananda bash Oct 15 '18 at 12:08

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

0

This will do what you want

read -a words <<< ${MAPFILE[0]}

And according to this, http://wiki.bash-hackers.org/commands/builtin/read you should always use a "-r", i.e.,

read -r -a words <<< ${MAPFILE[0]}

$ echo ${words[0]}
asdf1

Not the answer you're looking for? Browse other questions tagged or ask your own question.