Prevent variable expansion in Bash heredocument

147 Views Asked by At

I would like to create a longer multiline string in Bash without variable expansion. This text contains also items like ${varname} which is expanded according to the specification. However, I don't want to expand them in my script.

Dockerfile=`cat <<____
ARG BUILD_IMAGE
FROM ${BUILD_IMAGE}
...
# lots of further lines
____
`

I tried several variants ($\{, $\0173), but I could only solve it with

b='${'
...
FROM ${b}BUILD_IMAGE}
...

Which is really ugly. Is there any better way to solve this?

Edit:

Dockerfile=`cat <<'____'
ARG BUILD_IMAGE
FROM ${BUILD_IMAGE}
...
# lots of further lines
____
`

would solve the issue, but in this case I can't use any variable expansion.

Edit 2 - Answer:

Since the post has been closed, I answer my question here:

There is a difference between using backquote and $(. The issue is solved if I use the latter one. I had the problem, because I used the former one.

When the old-style backquote form of substitution is used, backslash retains its literal meaning except when followed by $, `, or . The first backquote not preceded by a backslash terminates the command sub‐ stitution. When using the $(command) form, all characters between the parentheses make up the command; none are treated specially.

This means in praxis:

text=$(cat <<__EOT__
Hello ${who}, hello \${who}!
__EOT__
)
echo $text

text=`cat <<__EOT__
Hello ${who}, hello \${who}!
__EOT__
`
echo $text

results in

Hello World, hello ${who}!
Hello World, hello World!
0

There are 0 best solutions below