Windows – Setting environment variables for Windows cmd temporarily, to run a program, in a single line

command lineenvironment-variableswindows

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.

https://stackoverflow.com/questions/8055371/how-do-i-run-two-commands-in-one-line-in-windows-cmd

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?

Best Answer

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" 
Related Question