Windows – Setting and using variable within same command line in Windows cmd.exe

command lineshellwindows

In Bash, I can do EDITOR=vim command and command will be run with EDITOR set to vim, but this won't affect the value of EDITOR in the shell itself. Is it possible to do this in cmd.exe?

Best Answer

Note that cmd /C "set "EDITOR=vim" && echo %EDITOR%" would not work.
Nor would cmd /C "setlocal ENABLEDELAYEDEXPANSION && set "EDITOR=vim" && echo !EDITOR!"

What would is the /V option, to enable delayed environment variable expansion using ! as delimiter.

C:\> cmd /V /C "set EDITOR=vim&& echo !EDITOR!"
vim

As noted below by maoizm, it is cmd /V /C, not cmd /C /V (which would not work)


I can't think of any practical reason you'd ever actually want this within the context of a single command

Typically, you need this when you have to replace a value used multiple times in a long command line.
For instance, to deploy a file to Nexus (in multiple lines for readability):

cmd /v /c "set g=com.agroup&& set a=anArtifact&& set v=1.1.0&& \
           mvn deploy:deploy-file -Dfile=C:\path\!a!-!v!.jar \
           -Dpackaging=jar -DgroupId=!g! -DartifactId=!a! -Dversion=!v! \
           -DrepositoryId=nexus 
           -Durl=http://myserver/nexus/content/repositories/my-repo/"

Instead of having to replace group, artifact (used 2 times) and version in a long and complex command line, you can edit them at the beginning of said command. It is clearer/easier to manipulate and change the parameter values.

Related Question