Search code examples
bashposixheredoc

In heredoc what is the delimiter for a single quote


Hello i'm programming a bash posix shell in c and i find this case where i didn't find the correct delimiter for the here doc.

bash --posix
cat << '
> '  <--- do not work
> \' <--- do not work

I would like to know what is the correct behavior in this specific case and where i can found more information about this.


Solution

  • You are attempting to use a here document:

    Here Documents: This type of redirection instructs the shell to read input from the current source until a line containing only a delimiter (with no trailing blanks) is seen. All of the lines read up to that point are then used as the standard input (or file descriptor n if n is specified) for a command.

    The format of here-documents is:

    [n]<<[-]word
      here-document
    delimiter
    

    No parameter and variable expansion, command substitution, arithmetic expansion, or pathname expansion is performed on word. If any part of word is quoted, the delimiter is the result of quote removal on word, and the lines in the here-document are not expanded. If word is unquoted, all lines of the here-document are subjected to parameter expansion, command substitution, and arithmetic expansion, the character sequence <newline> is ignored, and \ must be used to quote the characters , $, and `.

    If the redirection operator is <<-, then all leading tab characters are stripped from input lines and the line containing the delimiter. This allows here-documents within shell scripts to be indented in a natural fashion.

    As stated, If any part of word is quoted, the delimiter is the result of quote removal on word.

    The manual of bash also defines what a word is:

    • word: A sequence of characters treated as a unit by the shell. Words may not include unquoted metacharacters.
    • metacharacter: A character that, when unquoted, separates words. A metacharacter is a space, tab, newline, or one of the following characters: ‘|’, ‘&’, ‘;’, ‘(’, ‘)’, ‘<’, or ‘>’.

    This sort of implies that you can't use a single quote as word. I suggest using a real word that contains normal letters.

    cat -- <<'EOF'
       here-doc
    EOF
    

    References: