Use Variables Inside If and for Loop

Use Variables Inside If and for Loop

I have the following code:

echo off
set n=11
set m=12
set /a nme=3
set /a mdiff=nme-1
pause
if %n% NEQ %m% (
    if %mdiff% LEQ 3 (
        for /l %%C in (1,1,3) do (
            if %%C EQU 1 (
                set mon=Apr
            )
set num=1%mon%
        )
    )
)
echo %num%
pause

which gives me output 1 instead of 1Apr. However when I place set num=1%mon% outside all if and for loops it gives correct result.

Please explain me what happened here and how to obtain the correct result inside the loops.

Also, what is the maximum depth of if and for levels?

1

1 Answer

What you need to do is put a SetLocal EnableDelayedExpansion at the top of your script and use !s around your variables.

Delayed Expansion will cause variables to be expanded at execution time rather than at parse time, this option is turned on with the SETLOCAL command. When delayed expansion is in effect variables may be referenced using !variable_name! (in addition to the normal %variable_name% )

Delayed variable expansion is often useful when working with FOR Loops, normally an entire FOR loop is evaluated as a single command even if it spans multiple lines of a batch script.

Basically, the for loop gets parsed once. Each iteration of the loop, the statements get executes. By enabling this option, the variables can change on execution, without reparsing, i.e. within the loop.

@echo off
SetLocal EnableDelayedExpansion

set n=11
set m=12
set /a nme=3
set /a mdiff=nme-1
pause
if %n% NEQ %m% (
    if %mdiff% LEQ 3 (
        for /l %%C in (1,1,3) do (
            if %%C EQU 1 (
                set mon=Apr
                set num=1!mon!
            )
        )
    )
)
echo %num%
pause
7

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Maya Lin-Takahashi
Author

Maya Lin-Takahashi

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.