skip to Main Content

Is there a Windows equivalent to bash’s export? I want to set an environment variable so that it’s available to subsequent commands. I don’t want to setx a permanent env variable.

For example this works as expected with Docker for Windows in a Windows Terminal PowerShell Command Prompt. The FOO environment variable value is available in the container.

PS C:UsersOwner> docker run -e FOO=bar centos env
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
HOSTNAME=05b90a09d7fd
FOO=bar
HOME=/root

But how do I set an env variable in Windows with the equivalent of bash export so that it’s available without setting the value directly on each docker run command?
You can see here that set does not pass the value of FOO to the container.

PS C:UsersOwner> set FOO=bar
PS C:UsersOwner> docker run -e FOO centos env
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
HOSTNAME=6642033b3753
HOME=/root

I know I can create an env file and pass that to docker run but I’m trying to avoid that.

PS: I asked this question here but didn’t get an answer:
https://forums.docker.com/t/how-to-set-environment-variables-in-command-prompt-so-theyre-passed-in-docker-run-e-foo-e/106776/4

2

Answers


  1. From this answer, you can set a local environment variable for your shell with Powershell’s $env:VARIABLE_NAME.

    If I’m understanding your question correctly this should work for you if your objective is to just grab the variable name/value from the current terminal session.

    PS C:> $env:FOO = 'BAR'
    PS C:> docker run -it -e FOO alpine:3.9 /bin/sh
    / # env
    HOSTNAME=e1ef1d7393b2
    SHLVL=1
    HOME=/root
    TERM=xterm
    PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
    FOO=BAR
    PWD=/
    / # exit
    PS C:>
    

    An equivalent of unset would be one of the following (thanks to @mklement0 for the suggestion) :

    Remove-Item env:FOO
    
    # suggested by mklement0
    $env:FOO = $null
    
    Login or Signup to reply.
  2. Create a Powershell script docker_run.ps1

    And inside the script, you can define global variables and then use them in the docker run command written at the end of the script.

    This way it becomes easy to re-use the command easy to edit as well for any quick changes.

    The file would look as below:

    $global:ENV1="VALUE1"
    $global:ENV2="VALUE2"
    
    docker run -e ENV1=$ENV1 -e ENV2=$ENV2 --name Container_Name Image_Name
    

    And now just run this script inside the CMD as:

    1. powershell

    2. powershell docker_run.ps1

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search