Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dockerfile ARG substitution in a string in RUN command

In my Dockerfile I want to substitute a variable in a string.

ARG w=world
RUN echo 'Hello $w'

I want the output to be Hello world but the actual output is Hello $w

like image 495
lörf Avatar asked May 08 '18 17:05

lörf


People also ask

How do I pass ARG in Dockerfile?

ARG instruction defines a variable that can be passed at build time. Once it is defined in the Dockerfile you can pass with this flag --build-arg while building the image. We can have multiple ARG instruction in the Dockerfile. ARG is the only instruction that can precede the FROM instruction in the Dockerfile.

Can an ARG variable on Dockerfile be used by the running container?

ARG are also known as build-time variables. They are only available from the moment they are 'announced' in the Dockerfile with an ARG instruction up to the moment when the image is built. Running containers can't access values of ARG variables.

How do I pass an environment variable in docker run?

When we launch our Docker container, we can pass environment variables as key-value pairs directly into the command line using the parameter –env (or its short form -e). As can be seen, the Docker container correctly interprets the variable VARIABLE1.

What is Arg and ENV in Dockerfile?

From Dockerfile reference: The ARG instruction defines a variable that users can pass at build-time to the builder with the docker build command using the --build-arg <varname>=<value> flag. The ENV instruction sets the environment variable <key> to the value <value> .


2 Answers

Docker doesn't expand ARG values in the RUN command. Instead, it injects the ARG as an environment variable. The shell itself expands the variable, and all of the Linux shells I've used behave differently based on the type of quote.

The single quotes direct the shell not to expand anything, and you only need to escape the single quotes and escape characters. While the double quotes include variable expansion along with many other escape characters. See the man page on your shell for more details.

So the solution as you've already found is:

RUN echo "Hello $w"
like image 172
BMitch Avatar answered Oct 22 '22 08:10

BMitch


RUN echo "Hello $w" works fine. The ARG is resolved within double quotes.

like image 5
lörf Avatar answered Oct 22 '22 09:10

lörf