JustenDouma
JustenDouma

Reputation: 25

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

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

Upvotes: 2

Views: 955

Answers (2)

Squashman
Squashman

Reputation: 14290

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"
)

Upvotes: 2

phuclv
phuclv

Reputation: 41754

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

Upvotes: 3

Related Questions