在 heredoc 中对 shell 变量使用双引号

Using double quotes around shell variables in a heredoc

我编写了一个 bash 脚本并通过读取获得了一些用户输入。 我想将通过读取获得的变量放入 cat << EOF >> file 的文件中。 我的问题是每个变量都得到 "double quots"。 我怎样才能避免这种情况?

echo "Whats your name?"
read yourname

cat << EOF >> /path/to/file
Your Name is "${yourname}"

EOF

文件内容为:

Your Name is "djgudb"

应该是:

Your Name is djgudb

引号在 heredocs 中没有句法意义,所以如果您不希望它们是字面意思,请不要将它们放在那里。

echo "Whats your name?"
read yourname

cat << EOF >> /path/to/file
Your Name is ${yourname}

EOF

bash 手册说:

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  charac‐
   ter  sequence  \<newline>  is  ignored, and \ must be used to quote the
   characters \, $, and `.

所以你需要

cat << EOF >> /path/to/file
Your Name is ${yourname}

EOF