Using SET to set an empty value to a variable works nicely in a Windows XP .CMD script. However, the same SET command behaves differently in the same CMD interpreter when used directly from command-line:
Trying to test it in a CMD.EXE command-line:
C:\>set Q=
C:\>echo %Q%
%Q%
C:\>echo "%Q%"
"%Q%"
C:\>set Q=/Q
C:\>echo %Q%
/Q
C:\>echo "%Q%"
"/Q"
Trying to test it with a .CMD script like this:
set Q=
echo %Q%
echo "%Q%"
set Q=/Q
echo %Q%
echo "%Q%"
Running it:
C:\>c.cmd
C:\>set Q=
C:\>echo
ECHO is on.
C:\>echo ""
""
C:\>set Q=/Q
C:\>echo /Q
/Q
C:\>echo "/Q"
"/Q"
What am I missing?
Is that a nice joke from Redmond, or is there any sane explanation for this difference?
How am I supposed to test lines from a .CMD script when they behave differently when used in a command-line?
How do I properly set a variable to an empty string value in a CMD command-line and how do I reference that variable so that I get that empty string?
Best Answer
tl;dr - Problem you got there is that
echo %Q%
expands toecho
. Useecho.%Q%
Expanded Answer
echo
command got 4 behaviors:echo on
- enables echoing commands.echo off
- disables echoing commands.echo
- shows state of echoing commands option.echo ...
- puts...
and newline on the screen.If you pass variable to echo as an argument, and it's empty, it will expand to
echo
, and will show something like "ECHO is off."Many people use
echo.
command to display empty string (read: output newline), but not everybody knows thatecho.
can be used to excplicitly specify that you want output behavior. e.g.:echo.on
- will outputon
and newlineecho.off
- will outputoff
and newlineecho.
- will output newlineecho.something
- will outputsomething
and newlineecho.%Q%
- will output contents of%Q%
whether or not it's ""/"on"/"off" or whatever else.Keep in mind that there should not be space between
.
and arguments.See https://technet.microsoft.com/en-us/library/bb490897.aspx?f=255&MSPPError=-2147217396