Search code examples
windowsbatch-filecmddelayedvariableexpansion

Batch file : SET variable=string doesn't work


I've this code :

if %Ret:~6,4% EQU %Year% (
SET test=text
ECHO %test%
) else (
ECHO NO
)

The code enters in the if loop but it returns always Echo is off! I've pay attention to the space before and after the =. Any ideas?


Solution

  • Number #342 of this type of question this year.

    Percent expansion occours when a block is parsed, before any line is executed.
    So the echo %test% is expanded before the variable is set.

    Therefor exists the delayed expansion, which expands when a line is executed.

    setlocal EnableDelayedExpansion
    if "%Ret:~6,4%" EQU "%Year%" (
      SET test=text
      ECHO !test!
    ) else (
      ECHO NO
    )