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
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.
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.
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.
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> .
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"
RUN echo "Hello $w"
works fine. The ARG is resolved within double quotes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With