除了问题标题中提到的变量扩展之外,在将内联数据读取到<<EOL
...当数据包含反引号时,我还遇到了另一个令人担忧的问题`,它会导致错误。
两者都是替代问题,但相关选项是什么以及在哪里? ...(为什么内联读取的行为不同?)
这是脚本
#!/bin/bash
echo '==$BASH' | \
while IFS= read -r line ; do echo "# output 1: $line" ;done
echo '==$BASH'>junk
while IFS= read -r line ; do echo "# output 2: $line" ;done <junk
while IFS= read -r line ; do echo "# output 3: $line" ;done <<EOL
==$BASH
EOL
while IFS= read -r line ; do echo "# output 4: $line" ;done <<EOL
`my backtick test
EOL
这是输出
# output 1: ==$BASH
# output 2: ==$BASH
# output 3: ==/bin/bash
...: bad substitution: no closing "`" in `my backtick test
答案1
Shell 扩展是“此处文档”的主要好处之一。好消息是您可以将其关闭。
尝试:
while IFS= read -r line ; do echo "# output 3: $line" ;done <<'EOL'
==$BASH
EOL
while IFS= read -r line ; do echo "# output 4: $line" ;done <<'EOL'
`my backtick test
EOL
详情请参阅:
> info bash
<...>
3.6.6 Here Documents
--------------------
This type of redirection instructs the shell to read input from the
current source until a line containing only WORD (with no trailing
blanks) is seen. All of the lines read up to that point are then used
as the standard input for a command.
The format of here-documents is:
<<[-]WORD
HERE-DOCUMENT
DELIMITER
No parameter expansion, command substitution, arithmetic expansion,
or filename expansion is performed on WORD. If any characters in WORD
are 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. In the latter case,
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
DELIMITER. This allows here-documents within shell scripts to be
indented in a natural fashion.