3

Say I have a loop that goes through a file line-by-line via read. I would like to have both the original line, and the line split into different variables, which read does nicely. However, I can't seem to echo a variable, pipe it to read, and have the variables populated. Here's a base case:

echo "a b c d e f g" | read line
echo "Read obtained: $line"

The result:

Read obtained:

How can I make read do what I want? Or: Why am I wrong to ask read to do this, and what should I do instead?

2 Answers2

1

You can tell read read from pipeline as follows; Original answer by @yardena on SO

echo "a b c d e f g" | { read line; echo line=$line; }
αғsнιη
  • 41,407
0

the problem is scope. the variable has no value outside the subshell created by the pipe. Instead:

while read line; do echo "read obtained: ${line}"; done < <(echo "a b c d e f g")

use a loop however you want to. if you want to process text with one, do it. -C

αғsнιη
  • 41,407
chris
  • 21