Search code examples
batch-filevariablesdelayedvariableexpansion

Redefining the value of a variable that has been defined together with another variable


I am currently using this method from "jeb" to handle many variables. BAT-file: variable contents as part of another variable

setlocal EnableDelayedExpansion
set arr[1]=17
set arr[2]=35
set arr[3]=77
(
  set idx=2
  set /a var=arr[!idx!]
  echo !var!
)

Works well. The problem is that I need to set the value of some variables again. All my attempts have failed miserably.

set set arr[!idx!]=test
call set arr[!idx!]=test
set !arr[!idx!]!=test

Solution

  • Your question is not clear. I don't understand what you mean with "I need to set the value of some variables again". You should describe what you expect and what you really get instead. For this reason I can't offer an exact answer to your question, but just a series of examples:

    echo off
    setlocal EnableDelayedExpansion
    
    rem The target variable is "b1" or "b2", depending on *current* value of "i":
    set i=1
    set b1=var1
    set b2=var2
    call echo %%b%i%%%
    
    rem This works, but only *outside parentheses*
    set b%i%=var1changed
    call echo %%b%i%%%
    
    rem Inside paren, this works only when "i" var is not changed:
    (
    set b%i%=var1changed again
    call echo %%b%i%%%
    set i=2
    set b%i%=wrong: this should be b2, but it is b1
    call echo %%b%i%%%
    )
    set b
    
    rem Using delayed expansion for the index works always:
    (
    set i=1
    set b!i!=var1 again, inside paren
    call echo %%b!i!%%
    set i=2
    set b!i!=var2changed
    call echo %%b!i!%%
    )
    set b
    

    Output:

    var1
    var1changed
    var1changed again
    wrong: this should be b2, but it is b1
    b1=wrong: this should be b2, but it is b1
    b2=var2
    var1 again, inside paren
    var2changed
    b1=var1 again, inside paren
    b2=var2changed
    

    You may also use a FOR /F command for this management. Further details at this answer.