20

Wondering what is the right use of here-string (here-document) and pipe.

For example,

a='a,b,c,d'
echo $a | IFS=',' read -ra x
IFS=',' read -ra x <<< $a

Both methods work. Then what would be the difference between the two functionality?

Another problem that I have about "read" is that:

IFS=',' read x1 x2 x3 x4 <<< $a

does not work, x1 is valued as "a b c d", and x2, x3, x4 has no value

but if:

IFS=',' read x1 x2 x3 x4 <<< "$a"

I can get x1=a, x2=b, x3=c, x4=d Everything is okay!

Can anyone explain this?

Thanks in advance

dragonxlwang
  • 462
  • 5
  • 13
  • 4
    Your second question is interesting, but it should be asked separately. Putting two unrelated questions in the same post makes it much more difficult for the question to be found later by someone else with the same problem. – rici Aug 08 '13 at 04:46
  • 1
    I'm wondering if it might be worthwhile to mark this a dupe of http://stackoverflow.com/questions/41899075/running-sed-on-string-benefit-of-using-echo-pipe-over -- the question there is asked with less digression, and is thus potentially more useful to folks who are strictly interested in the pipeline-vs-herestring question given in the title. – Charles Duffy Jan 27 '17 at 20:12

1 Answers1

20

In the pipeline, two new processes are created: one for a shell to execute the echo command, and one for a shell to execute the read command. Since both subshells exit after they complete, the x variable is not available after the pipeline completes. (In bash 4, the lastpipe option was introduced to allow the last command in a pipeline to execute in the current shell, not a subshell, alleviating the problem with such pipelines).

In the second example, no extra process is need for the here string (a special type of here document that consists of a single line), so the value of x is in fact set in the current shell, making it available for use later in the script/session.

chepner
  • 497,756
  • 71
  • 530
  • 681
  • thx, but I am not quite understanding about the pipeline resulted unavailability of variables: I experiment with GNU bash version 3.2.48(1), and I can still echo $x after the pipeline ends. And what is the different purpose of the two methods? (function, usage) – dragonxlwang Aug 08 '13 at 01:22
  • 2
    `x` must have had a previous value, because the pipeline will not set the value of `x` in the current shell. Here documents were created, in part, to avoid the subshell problem introduced by using pipelines. – chepner Aug 08 '13 at 01:31
  • I see, thanks!! And please help me with the added part of question. Thanks! – dragonxlwang Aug 08 '13 at 01:49