Multiline syntax for piping a heredoc; is this portable?

前端 未结 4 1521
北恋
北恋 2020-12-12 14:54

I\'m familiar with this syntax:

cmd1 << EOF | cmd2
text
EOF

but just discovered that bash allows me to write:

cmd1 &         


        
4条回答
  •  不知归路
    2020-12-12 15:12

    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 and continues until there is a line containing only the delimiter and a , with no 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 <

    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.

提交回复
热议问题