Is there a way to set environment variables for a single command on Windows like ENVVAR=abc command on Unix?
Variables set by set command on Windows seem to remain for the following commands, but this is not what I want.
Is there a way to set environment variables for a single command on Windows like ENVVAR=abc command on Unix?
Variables set by set command on Windows seem to remain for the following commands, but this is not what I want.
From the current cmd shell:
You have to clear the variable yourself.
set "ENVVAR=abc" && dir & set ENVVAR=
From a batch file:
You can use setlocal and endlocal.
@echo off
setlocal
set "ENVVAR=abc" && dir
endlocal
Use a child cmd shell:
You can use cmd /c to create a child shell.
The variable is set in the child shell and doesn't affect the parent shell (as pointed out in a comment by jpmc26).
cmd /C "set ENVVAR=abc && dir"
cmd process and set them there. E.g., cmd /C "set ENVVAR=abc && dir". Since it won't affect the parent process, it will be effectively "cleared" on exit.
– jpmc26
Mar 06 '16 at 19:48
abc but to abc! The extra space can simply be fixed by leaving it out before the &&. You might want to edit your answer, maybe even explicitly pointing out this issue because it might be surprising for unix affine people. It's extra hard to debug because output of set without any parameters when copied from a cmd.exe window does not include such trailing spaces!
– purefanatic
Apr 04 '23 at 16:55