How to set/use an empty string value in a variable in Windows XP CMD.EXE command-line?

Solution 1:

tl;dr - Problem you got there is that echo %Q% expands to echo. Use echo.%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 that echo. can be used to excplicitly specify that you want output behavior. e.g.:

  • echo.on - will output on and newline
  • echo.off - will output off and newline
  • echo. - will output newline
  • echo.something - will output something and newline
  • echo.%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

Solution 2:

I met exactly the same problem in my script. Currently I didn't find a way to set a variable to empty string. I just found how to initialize it with one space:

set "Var= "

Those quotation marks are optional. But they really help to see that space explicitly and preserve it in case of terminal whitespace cleanup procedures.

More information you can find here: SET command.

Solution 3:

While you can check whether a variable is empty or not, if you want to concatenate a variable to a string with support for empty/null values, a possible workaround would be to prefix all your values with a dummy character, and skip this character whenever you use this variable:

set q=0
set q2=%q:~1%string

test:

set q=0_
echo %q%
echo %q:~1%concat%q:~1%

set q=0
echo %q%
echo %q:~1%concat%q:~1%

The result will be _concat_ in the first case and concat in the second.