Home > Mobile >  How to use delayed expansion on a variable like %%a or %1?
How to use delayed expansion on a variable like %%a or %1?

Time:09-25

I'm trying to make a batch file I call from another batch file, but the variables don't work, all the results are "a", while the expected result would be option1=a, option2=b, etc.

Here's the code to demonstrate the issue:

call temp.bat a b c d e f g h i j k l m n o p q r s t e u v w x y z
pause
exit

and for temp.bat:

set Number=0
for %%a in (%*) do set /a Number =1

for /l %%a in (1,1,%Number%) do (
    set option%%a=%1
    shift
)
exit /b

I've tried !%1! with empty results; %%1% gave "%1" as the result; %1% had the same result as just using %1

CodePudding user response:

You can force another level of indirection by using call. It'll expand %%1 to %1 before evaluating

for /l %%a in (1,1,%Number%) do (
    call set option%%a=%%1
    shift
)

See also an alternative here: Batch-Script - Iterate through arguments

CodePudding user response:

You could do this with one FOR command which would be much more efficient.

Using the CALL Method

@echo off

set Number=0
for %%a in (%*) do (
    set /a Number =1
    call set "option%%Number%%=%%a"
)

Using Delayed Expansion

@echo off
setlocal enabledelayedexpansion
set Number=0
for %%a in (%*) do (
    set /a Number =1
    set "option!Number!=%%a"
)
  • Related