0

I have a requirement where I need to increment the variable and store a value into that. For example: Suppose Initially variable Batch1 has value 1000. Now i need to dynamically create subsequent batch variables and store incremental values into those variables e.g. next dynamically created variable should be Batch2 and value it hold should be 1001. Similarly Batch3=1003, Batch4=1004 and so on...

Is this possible in Batch scripting?

ImranKhan
  • 35
  • 3
  • I suggest you to read about [arrays](http://stackoverflow.com/questions/10166386/arrays-linked-lists-and-other-data-structures-in-cmd-exe-batch-script/10167990#10167990) in Batch files. – Aacini Feb 22 '14 at 15:20

2 Answers2

0

You could do this with a method:

@echo off
Rem Start Code
goto :start

:Update_Method
if "%1"=="" goto :eof
if "%2"=="" goto :eof
if "%3"=="" goto :eof
setlocal enabledelayedexpansion
set base=%1
set /a start=%2
set /a end=%3
for /l %%a in (1,1,%end%) do (set /a !base!%%a=!start!+%%a-1)
set base=
set start=
set end=
goto :eof

:start
Rem Start Rest of Code

And that should do what you want. Simply use as:

call Update_Method Batch 1000 10

And that will create:

Batch1=1000
Batch2=1001
Batch3=1002
...
Batch10=1009

Call it whenever you want to "dynamically" change the values.

I still have to test this, but it doesn't seem faulty.

Mona

Monacraft
  • 6,510
  • 2
  • 17
  • 29
0
@echo off

    setlocal
    for /l %%a in (1 2 50) do call :incrementalSet batch %%a
    set batch
    endlocal


    exit /b

:incrementalSet basename value
    setlocal enableextensions enabledelayedexpansion
    set "last=0"

    :: if the name of the variable can collide with something in the environment,
    :: the following line should be used. If not, it is an unnecessary overhead
    :: for /f "tokens=1 delims==" %%y in ('set %~1 2^>nul^|findstr /r /b /c:"%~1[0-9][0-9]*="') do (

    :: if the base name does not contain numbers, the loop can be reduced to 
    :: for /f "tokens=1 delims=%~1=" %%y in ('set %~1 2^>nul') do if %%y gtr !last! set "last=%%y"

    for /f "tokens=1 delims==" %%y in ('set %~1 2^>nul') do (
        set "test=%%y"
        set "test=!test:*%~1=!"
        if defined test if !test! gtr !last! set "last=!test!"
    )
    set /a "last+=1"
    endlocal & set "%~1%last%=%~2" & exit /b
MC ND
  • 69,615
  • 8
  • 84
  • 126