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?

gaazkam
  • 1,410

1 Answers1

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
Chai Ang
  • 148