Sunday, 5 November 2017

windows - 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?



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

No comments:

Post a Comment

Where does Skype save my contact's avatars in Linux?

I'm using Skype on Linux. Where can I find images cached by skype of my contact's avatars? Answer I wanted to get those Skype avat...