I have seen Setting and getting Windows environment variables from the command prompt?, but my question is slightly different.

Say I have a terminal program, myprogram.c -> myprogram.exe, which reads environment variables; say:

char *valueMYVAR = getenv("MYVAR");
printf("MYVAR is %s\r\n", (valueMYVAR==NULL)?"":valueMYVAR );

Now, if I'm in Linux bash, I can set the environment variable temporarily, just for that execution of the program, by simply writing it out on the command line, as in:

$ MYVAR=1 ./myprogram.exe

How could I do the same, if I am using the Windows Command Prompt (cmd.exe)? I have tried:

> SET MYVAR=1 myprogram.exe

... but it doesn't work - in the sense that myprogram.exe is not run at all, probably being interpreted as being part of the command line for the SET command.

Is this kind of a thing doable in Windows Command Prompt? If relevant, I use Windows 10.

EDIT: Found these:

Is there something like Command Substitution in WIndows CLI?

In Windows the '( )' operator has a similar behavior as the Bash command substitution.


Like this on all Microsoft OSes since 2000, and still good today:
dir & echo foo

So, I've tried:

> (SET MYVAR=1 && myprogram.exe)

... and this actually works - except, it seems the parentheses in Windows are not a "subshell" (or "subprocess"), and therefore setting the value "leaks" onto the current shell, which I don't want (in other words, if I just run myprogram.exe after the above command, it will still pick up MYVAR=1, whereas on Linux, MYVAR in that case would remain unset).

So, is there a way to do this on a single command line - and temporarily?

  • Thanks @Biswapriyo - that looks like it will work; though it would have been nice not to have to remember to "unset" the variable in the end – sdbbs Feb 14 at 12:31

You could run a batch file with a setlocal

or on cmd line start another cmd.exe which inherits the current environment but changes are volatile.

cmd /c "SET MYVAR=1&myprogram.exe" 
  • Thanks a lot @LotPings - the starting of another cmd.exe does exactly what I wanted (makes the environment variable changes not persistent) – sdbbs Feb 14 at 15:58

Try this command:

set Foo=bar & abc.exe & set Foo=

This command does:

  1. Set Foo variable with bar value.
  2. Run abc.execommand.
  3. Unset Foo variable by adding blank value.

Your Answer

By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.