简体   繁体   English

管道化heredoc的多行语法; 这是便携式的吗?

[英]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:但刚刚发现 bash 允许我写:

cmd1 << EOF |
text
EOF
cmd2

(the heredoc is used as input to cmd1, and the output of cmd1 is piped to cmd2). (heredoc 用作 cmd1 的输入,cmd1 的 output 通过管道传送到 cmd2)。 This seems like a very odd syntax.这似乎是一个非常奇怪的语法。 Is it portable?它是便携式的吗?

Yes, the POSIX standard allows this.是的,POSIX 标准允许这样做。 According to the 2008 version: 根据2008版:

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. here-document 应被视为一个单词,从下一个<newline>开始并一直持续到有一行仅包含分隔符和<newline> ,中间没有<blank>字符。 Then the next here-document starts, if there is one.然后下一个 here-document 开始,如果有的话。

And includes this example of multiple "here-documents" in the same line:并在同一行中包含多个“here-documents”的示例:

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: shell 语法(在链接页面的下方)包括以下定义:

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.因此,pipe 符号后面可以跟一个行尾,但仍被视为流水线的一部分。

Yes it's in the POSIX shell grammar.是的,它在 POSIX shell 语法中。 You can also have more than one here-doc for the same command (some other examples use two cat invocations, but this works as well):对于同一个命令,您还可以有多个 here-doc (其他一些示例使用两个cat调用,但这也适用):

cat <<EOF1 <<EOF2
first here-doc
EOF1
second here-doc
EOF2

This is contrived (using 2 here-docs for stdin), but if you think of providing input for different file descriptors it immediately makes sense.这是人为的(使用 2 个 here-docs 作为标准输入),但如果您考虑为不同的文件描述符提供输入,它立即有意义。

There's also the possibility to drop the cat entirely .也有可能完全丢弃cat Why not make the here-document directly available to cmd :为什么不直接将 here-document 提供给cmd

cmd << EOF
input
here
EOF

Hmm, I suppose yes, according to the test in bash in POSIX mode:嗯,我想是的,根据 POSIX 模式下 bash 中的测试:

$ bash --posix
$ cat <<EOF |
> ahoj
> nazdar
> EOF
> sed 's/a/b/'
bhoj
nbzdar

Hi, check this, for example嗨,检查一下,例如

#!/bin/sh
( base32 -d | base64 -d )<<ENDOFTEXT
KNDWW42DNNSHS5ZXPJCG4MSVM5MVQVT2JFCTK3DELBFDCY2IIJYGE2JUJNHWS22LINVHQMCMNVFD
CWJQIIZVUV2JOVNEOVJLINTW6PIK
ENDOFTEXT

regards问候

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM