0

I have the following DOS commands in a batch file:

SET "REALM="
ECHO %REALM:/=.%

SET "REALM=Westeros"
ECHO %REALM:/=.%

SET "REALM=Westeros/"
ECHO %REALM:/=.%

The last two commands give me the expected results: Westeros Westeros.

But the first, replacing / for . on an empty variable, gives: /=.

Why does this happen and how can I do this right?

Martin Giessen
  • 147
  • 1
  • 7

2 Answers2

3

It's a problem/feature of the parser with undefined variables.

How does the Windows Command Interpreter (CMD.EXE) parse scripts?

See also How does the Windows Command Interpreter (CMD.EXE) parse scripts?

To solve this you need to test first for undefined variables like.

set "REALM="
if defined REALM SET "REALM=%REALM:/=.%"
echo( %REALM%

I used here echo( to avoid the output of "ECHO IS OFF" when the variable is empty.

Community
  • 1
  • 1
jeb
  • 70,992
  • 15
  • 159
  • 202
  • So, as I understand it, if REALM is undefined then the command-line processor will remove %REALM: from the command-line, leaving "/=." and continue the scan. Thus; To solve this puzzle I would have to define an empty variable, which I can't, to get the expected result. – Martin Giessen Sep 05 '14 at 07:27
  • Yes, replacing works only when the variable is defined, else it fails and you get rubbish – jeb Sep 05 '14 at 13:42
0

If you make aSET "REALM=". Then %Realm% is undefined (without any value).

SachaDee
  • 8,843
  • 2
  • 18
  • 29