错误替换:在heredoc / EOF 中没有关闭“`”

el-*_*dee 7 escape-characters command-substitution here-document

我想打印一个man 风格的使用消息来描述一个像这样输出的 shell 函数man find

NAME
       find - search for files in a directory hierarchy

SYNOPSIS
       find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression]

DESCRIPTION
       This  manual  page  documents the GNU version of find.  GNU find searches the directory tree rooted at each
       given starting-point by evaluating the given expression from left to  right,  according  to  the  rules  of
       precedence  (see section OPERATORS), until the outcome is known (the left hand side is false for and opera?
       tions, true for or), at which point find moves on to the next file name.  If no  starting-point  is  speci?
       fied, `.' is assumed.

OPTIONS
Run Code Online (Sandbox Code Playgroud)

我正面临关于 ` 字符的错误消息。
以下简单脚本显示了错误:

~$ cat <<EOF
`.'
EOF

bash: bad substitution: no closing "`" in `.'
Run Code Online (Sandbox Code Playgroud)

我虽然heredoc是通过粘贴字符串来回显字符串而不必转义其内容(例如引号等)的一种很酷的方法...... 我认为我错了:/

有人可以解释这种行为吗?可以heredoc接受`字符吗?

编辑2:我接受的答案引述这里文档 <<'END_HELP',但我作为最终不会使用它的这种完整的手动输出的kusalananda确实暗示

编辑 1:(供以后阅读)使用此处引用的文档的限制是防止tputhere-document.
为此,我执行了以下操作:

  1. 未加引号here-document,用于tput要执行的命令
  2. 通过转义反引号来防止“错误替换”错误
  3. 使用tputhere-document

例子:

normal=$( tput sgr0 ) ;
bold=$(tput bold) ;

cat <<END_HELP # here-document not quoted
${bold}NAME${normal}
       find - search for files in a directory hierarchy

${bold}SYNOPSIS${normal}
       find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression]

${bold}DESCRIPTION${normal}
       This  manual  page  documents the GNU version of find.  GNU find searches the directory tree rooted at each
       given starting-point by evaluating the given expression from left to  right,  according  to  the  rules  of
       precedence  (see section OPERATORS), until the outcome is known (the left hand side is false for and opera?
       tions, true for or), at which point find moves on to the next file name.  If no  starting-point  is  speci?
       fied, \`.' is assumed.
END_HELP

unset normal ;
unset bold ;
Run Code Online (Sandbox Code Playgroud)

在这里,请注意作为错误来源的转义反引号:

\`.'
Run Code Online (Sandbox Code Playgroud)

Kus*_*nda 9

反引号引入了命令替换。由于没有引用 here-document,这将由 shell 解释。shell 会抱怨,因为命令替换没有结尾反引号。

要引用此处的文档,请使用

cat <<'END_HELP'
something something help
END_HELP
Run Code Online (Sandbox Code Playgroud)

或者

cat <<\END_HELP
something something help
END_HELP
Run Code Online (Sandbox Code Playgroud)

关于您对解决此问题的意见:

实用程序很少自己输出完整的手册,但可能会提供概要或基本使用信息。这很少,如果有的话,是彩色的(因为它的输出可能不会被定向到终端或寻呼机之类的less)。真正的手册通常使用groff或专用的手册页格式器进行排版,mandoc并且与代码完全分开处理。

  • @el-teedee Utilities 很少自己输出完整的手册,但可能会提供概要或基本使用信息。这很少(如果有的话)着色(因为它的输出可能不会定向到终端)。真正的手册通常使用 `groff` 排版,并与代码完全分开处理。 (2认同)