4

I'm creating a file with EOF like this:

cat <<EOF > Dockerfile
RUN apt-get update -y \
  && apt-get install -y \
    bsdtar \
    git \
    locales
EOF

But the result is:

RUN apt-get update -y   && apt-get install -y     bsdtar     git     locales

I want to keep the backslash and the linebreak

3

You need to quote the EOF token:

cat <<"EOF" > Dockerfile
RUN apt-get update -y \
  && apt-get install -y \
    bsdtar \
    git \
    locales
EOF

If you want to expand variables too, you need to escape the backslashes and not use any quotes.

Here's the corresponding man bash section.

      [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 `.
  • But what do I have to do if I need to use some variables (not shown in my example code)? – user3142695 Oct 21 '17 at 7:50
  • They will get expanded as in the common shell double quoting. If this is not desired, use single quotes, eg. cat <<'EOF' > Dockerfile. – Tomasz Oct 21 '17 at 7:52
  • I think that's not the case (i.e. with double quotes around EOF, the variables will not be expanded). Are you sure? The correct answer is in the comment by @dave_thompson_085 : double the backslashes. – Rastapopoulos Oct 21 '17 at 9:25
  • @Rastapopoulos I thought so, but it looks like I was wrong. – Tomasz Oct 21 '17 at 9:28
  • @user3142695 As in the comment above, double quoting stops expansion too. So to both expand variables and keep the backslashes, you need to escape the backslashes and not use any quotes. – Tomasz Oct 21 '17 at 9:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.