1 摘自wikipedia的介绍
In computer science, a here document (here-document, heredoc, hereis, here-string or here-script) is a file literal or input stream literal: it is a section of a source code file that is treated as if it were a separate file. The term is also used for
a form of multiline string literals that use similar syntax, preserving line breaks and other whitespace (including indentation) in the text.
Here documents originate in the Unix shell, and are found in sh, csh, ksh, Bash and zsh, among others. Here document-style string literals are found in various high-level languages, notably the Perl programming language (syntax inspired by Unix shell) and languages influenced by Perl, such as PHP and Ruby. Other high-level languages such as Python and Tcl have other facilities for multiline strings.
For here documents, whether treated as files or strings, some languages treat it as a format string, allow variable substitution and command substitution inside the literal.
The most common syntax for here documents, originating in Unix shells, is << followed by a delimiting identifier (often EOF or END), followed, starting on the next line, by the text to be quoted, and then closed by the same delimiting identifier on its own line. This syntax is because here documents are formally stream literals, and the content of the document is redirected to stdin (standard input) of the preceding command; the here document syntax is by analogy with the syntax for input redirection, which is < "take input from the output of the following command".
Other languages often use substantially similar syntax, but details of syntax and actual functionality can vary significantly. When used simply for string literals, the << does not indicate indirection, but is simply a starting delimiter convention. In
some languages, such as Ruby, << is also used for input redirection, thus resulting in << being used twice if one wishes to redirect from a here document string literal.
2 shell的here document
2.1 原理与作用
如wikipedia所介绍,here document就是声明相关部分是独立于脚本的一个document。其与改脚本的关系为,document的内容为改脚本中与它所在一行的preceding command的标准输入。
经常用户交互命令的输入。
2.2 格式
shell <<定界符 重定向和管道相关
line1
line2
……
定界符
两个定界符需要一致。定界符之间的部分被视为document,除了重定向相关的内容。document中可以使用变量。
2.3 例子
这里举一个pstack中使用的here document作为例子。
$GDB --quiet $readnever -nx /proc/$1/exe $1 <<EOF 2>&1 |
$backtrace
EOF
sed -n \
-e 's/^(gdb) //' \
-e '/^#/p' \
-e '/^Thread/p'2.4 与标准输入重定向冲突
前面介绍here document的原理是将document作为command的标准输入,那么当here document与标准输入重定向共同作用的时候会出现什么情况呢?
答案是标准输入重定向会覆盖here document。可以理解为here document将document输入到“屏幕输入”,默认的“屏幕输入”就是标准输入。当对标准输入进行重定向的时候,那么here document就不会输入到标准输入了。
[~]$ cat <<EOF >hh
> a
> b
> c
> EOF
[~]$ cat hh
a
b
c
[~]$ cat <<EOF >hh </dev/null
> a
> b
> c
> EOF
[~]$ cat hh
深入解析heredocument在Shell脚本中的应用与特性

本文详细介绍了heredocument的概念、原理、语法、使用场景及注意事项,包括如何在Shell脚本中利用heredocument实现用户交互、字符串变量的替换与命令重定向,并探讨了其与标准输入重定向之间的冲突。通过具体实例展示了heredocument在实践中的应用,以及在不同语言环境下其功能的差异。
1940

被折叠的 条评论
为什么被折叠?



