2

I've simple cmd script:

@echo off
if  %1.==. (
    echo Missing argument
) else (
    SET somevar=%1
    echo %1
    echo %somevar%
)

Problem with that is it looks like echo of variable somevar in else block are running before variable is set. Every time I run this, echo of argument working well but echo of variable shows value from previous run. This is happening only in if/else block and I don't understand why. If I modify script like that:

@echo off
if  %1.==. (
    echo Missing argument
    exit /B
)

SET somevar=%1
echo %1
echo %somevar%

result is as I expected. Running the script alternately with different argument gives clear view of an issue.

I've read some posts eg. How to clear variables after each batch script run? but I think it's different kind of problem.

So, is there any way to protect against such behavior inside IF/ELSE statement?

DaszuOne
  • 759
  • 1
  • 6
  • 18

1 Answers1

3
@echo off
if  %1.==. (
    echo Missing argument
) else (
    SET somevar=%1
    echo %1
    CALL echo %%somevar%%
)

or

@echo off
SETLOCAL EnableDelayedExpansion
if  %1.==. (
    echo Missing argument
) else (
    SET somevar=%1
    echo %1
    echo !somevar!
)

Resources (required reading):

JosefZ
  • 28,460
  • 5
  • 44
  • 83