使用 EOF 保留反斜杠和换行符

use*_*695 7 shell

我正在创建一个这样的文件EOF

cat <<EOF > Dockerfile
RUN apt-get update -y \
  && apt-get install -y \
    bsdtar \
    git \
    locales
EOF
Run Code Online (Sandbox Code Playgroud)

但结果是:

RUN apt-get update -y   && apt-get install -y     bsdtar     git     locales
Run Code Online (Sandbox Code Playgroud)

我想保留反斜杠和换行符

小智 10

您需要引用 EOF 令牌:

cat <<"EOF" > Dockerfile
RUN apt-get update -y \
  && apt-get install -y \
    bsdtar \
    git \
    locales
EOF
Run Code Online (Sandbox Code Playgroud)

如果您也想扩展变量,您需要转义反斜杠而不使用任何引号。

这是相应的man bash部分。

      [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  charac?
   ter  sequence  \<newline>  is  ignored, and \ must be used to quote the
   characters \, $, and `.
Run Code Online (Sandbox Code Playgroud)

  • 它们将像在通用 shell 双引号中一样被扩展。如果不需要,请使用单引号,例如。`cat &lt;&lt;'EOF' &gt; Dockerfile`。 (2认同)