Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
822 views
in Technique[技术] by (71.8m points)

bash - What's the difference between "here string" and echo + pipe

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...