Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to I expand arguments in a Docker RUN command using Powershell?

I have a Dockerfile that uses a Windows Nano Server base image and uses Powershell as shell:

FROM microsoft/nanoserver
SHELL ["powershell"]

I now want to define a variable (or pass it in via --build-arg) using the ARG command and then use it in a RUN command, but I can't seem to get it to work. I've tried:

ARG mydir=tmp
RUN mkdir %mydir%
RUN mkdir $mydir

But none of these work.

How do I tell docker / powershell to expand my variable correctly?

like image 818
GeorgS Avatar asked Jun 04 '26 19:06

GeorgS


1 Answers

Arguments passed to a Powershell command run via RUN are not substituted by Docker, but by Powershell itself. They are treated like normal environment variables by Powershell, so the correct syntax is:

FROM microsoft/nanoserver
SHELL ["powershell"]
ARG mydir=tmp
RUN mkdir $env:mydir

So in the same way you can also expand normal environment variables:

RUN mkdir $env:LOCALAPPDATA\$env:mydir

Note that this is only valid within the context of a RUN command. With other Docker commands variables still expand using the normal notation:

COPY ./* $mydir

It's confusing on Windows/Powershell as on Linux containers using a bash shell the notation is the same in both cases.

like image 200
GeorgS Avatar answered Jun 06 '26 17:06

GeorgS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!