mbergmann
mbergmann

Reputation: 95

Using double quotes around shell variables in a heredoc

I write a bash script and get some user input with read. I want to put the variables, I got by read, in a file with cat << EOF >> file. My problem is that every variable get "double quots". How can I prevent this?

echo "Whats your name?"
read yourname

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

EOF

The content of the file is:

Your Name is "djgudb"

It should be:

Your Name is djgudb

Upvotes: 5

Views: 6944

Answers (2)

sjsam
sjsam

Reputation: 21955

The bash manual says :

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 `.

So you need

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

EOF

Upvotes: 4

Charles Duffy
Charles Duffy

Reputation: 295316

Quotes have no syntactic meaning in heredocs, so don't put them there if you don't want them to be literal.

echo "Whats your name?"
read yourname

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

EOF

Upvotes: 10

Related Questions