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

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.


You can do it in windows like this no need for installing anything.

cmd /C "set EDITOR=vim && set"

You'll see a list of variables and you'll see EDITOR=vim, now run "set" again and it won't be listed.

You can do multiple &&'s to add additional commands:

cmd /C "set EDITOR=vim && do this && do that && otherstuff"

EDIT: /C exits the new cmd right away after running, if you produce output with the new one it will still be visible in the parent window.

You can opt to use /K in which case the new cmd window stays open at the end of the run.


you can use ported util env from package CoreUtils in GnuWin32 http://gnuwin32.sourceforge.net/

  1. Setup it
  2. Check what directory with env.exe exists in %PATH% variable
  3. Use same way like linux version env EDITOR=vim command