When I use the cmd
command with two actions anded together, the spaces are removed from the second action and then doesn't run correctly. When I run
C:\>cmd /C "set "MYVAR=MYVAL" && echo %MYVAR%"
I expect
MYVAL
But I get
'echo%MYVAR%' is not recognized as an internal or external command,
operable program or batch file.
%MYVAR%
Why is this happening?
UPDATE
I have figured what is causing the problem, but I don't know how to fix it.
I created a batch file I called .cmdrc.bat
that runs whenever I open a new cmd window. Effectively giving me custom functions and aliases with DOSKEY
. This was causing problems with programs that launched their own cmd window, so I tried to detect if cmd was opened with a program or by the user, and then only run if a user launched it.
To do this I stripped spaces and quotes from %COMSPEC%
and %CMDCMDLINE%
and compared them. But for some reason, this appears to be changing the value of %CMDCMDLINE%
to the version without spaces, causing the original issue.
Here is the relevant code:
:: only run this script if cmd.exe was launched by the user and not a program
:: this is done by checking if this prompt was launched with options
:: get the command that user would run and remove any spaces or double quotes
set cmdloc=%COMSPEC%
set cmdloc=%cmdloc: =%
set cmdloc=%cmdloc:"=%
:: get the command that was run to launch this instance and remove any spaces or double quotes
set cmdcall=%CMDCMDLINE%
set cmdcall=%cmdcall: =%
set cmdcall=%cmdcall:"=%
:: now compare them and exit if they are not the same
if /I not "%cmdloc%" == "%cmdcall%" (exit /B)
:: no flags were used when launching this instance of cmd.exe,
:: assume it was launched by the user and run all following commands
Why is %CMDCMDLINE%
updating with the new value?
What is a better way to detect if the user launched cmd?