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
951 views
in Technique[技术] by (71.8m points)

bash - Multiline syntax for piping a heredoc; is this portable?

I'm familiar with this syntax:

cmd1 << EOF | cmd2
text
EOF

but just discovered that bash allows me to write:

cmd1 << EOF |
text
EOF
cmd2

(the heredoc is used as input to cmd1, and the output of cmd1 is piped to cmd2). This seems like a very odd syntax. Is it portable?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Yes, the POSIX standard allows this. According to the 2008 version:

The here-document shall be treated as a single word that begins after the next <newline> and continues until there is a line containing only the delimiter and a <newline>, with no <blank> characters in between. Then the next here-document starts, if there is one.

And includes this example of multiple "here-documents" in the same line:

cat <<eof1; cat <<eof2
Hi,
eof1
Helene.
eof2

So there is no problem doing redirections or pipes. Your example is similar to something like this:

cat file |
cmd

And the shell grammar (further down on the linked page) includes these definitions:

pipe_sequence    :                             command
                 | pipe_sequence '|' linebreak command

newline_list     :              NEWLINE
                 | newline_list NEWLINE
                 ;
linebreak        : newline_list
                 | /* empty */

So a pipe symbol can be followed by an end-of-line and still be considered part of a pipeline.


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

...