用于管道heredoc的多行语法; 这便携式吗?

Wil*_*ell 122 bash shell pipe heredoc sh

我熟悉这种语法:

cmd1 << EOF | cmd2
text
EOF
Run Code Online (Sandbox Code Playgroud)

但刚刚发现bash允许我写:

cmd1 << EOF |
text
EOF
cmd2
Run Code Online (Sandbox Code Playgroud)

(heredoc用作cmd1的输入,cmd1的输出用于cmd2).这似乎是一个非常奇怪的语法.它是便携式的吗?

Ned*_*ily 95

是的,POSIX标准允许这样做. 根据2008版:

here-document应被视为一个单词,它在下一个文本之后开始,<newline>并一直持续到一行只包含分隔符和a <newline>,<blank>其间没有字符.然后下一个here-document开始,如果有的话.

并在同一行中包含多个"here-documents"的示例:

cat <<eof1; cat <<eof2
Hi,
eof1
Helene.
eof2
Run Code Online (Sandbox Code Playgroud)

因此,重定向或管道没有问题.您的示例类似于以下内容:

cat file |
cmd
Run Code Online (Sandbox Code Playgroud)

shell语法(进一步在链接页面上)包括以下定义:

pipe_sequence    :                             command
                 | pipe_sequence '|' linebreak command

newline_list     :              NEWLINE
                 | newline_list NEWLINE
                 ;
linebreak        : newline_list
                 | /* empty */
Run Code Online (Sandbox Code Playgroud)

因此,管道符号后面可以跟一个行尾符号,仍然被视为管道的一部分.


Jen*_*ens 21

是的,它在POSIX shell语法中.您也可以为同一个命令使用多个here-doc(其他一些示例使用两个cat调用,但这也适用):

cat <<EOF1 <<EOF2
first here-doc
EOF1
second here-doc
EOF2
Run Code Online (Sandbox Code Playgroud)

这是设计的(使用2 here-docs for stdin),但如果你想为不同的文件描述符提供输入,它立即是有道理的.

还有可能完全放弃cat.为什么不将here-document直接提供给cmd:

cmd << EOF
input
here
EOF
Run Code Online (Sandbox Code Playgroud)

  • 它可以在什么 bash 版本上运行?使用bash 4.4.19(在ubuntu 18.04.02上)和bash 5.0(docker镜像),我只得到了第二个here-doc。或者也许有一个特定的选项? (2认同)

TMS*_*TMS 14

嗯,我想是的,根据POSIX模式中的bash测试:

$ bash --posix
$ cat <<EOF |
> ahoj
> nazdar
> EOF
> sed 's/a/b/'
bhoj
nbzdar
Run Code Online (Sandbox Code Playgroud)

  • 在POSIX模式下运行bash会关闭*某些*扩展名,但几乎不会关闭所有扩展名。因此,尽管就POSIX所允许的观点而言,这个答案是正确的,但其推理并不十分有效。 (2认同)

小智 9

您好,请检查一下,例如

#!/bin/sh
( base32 -d | base64 -d )<<ENDOFTEXT
KNDWW42DNNSHS5ZXPJCG4MSVM5MVQVT2JFCTK3DELBFDCY2IIJYGE2JUJNHWS22LINVHQMCMNVFD
CWJQIIZVUV2JOVNEOVJLINTW6PIK
ENDOFTEXT
Run Code Online (Sandbox Code Playgroud)

问候