2

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

phuclv
  • 37,963
  • 15
  • 156
  • 475
  • 2
    [Argument references](https://ss64.com/nt/syntax-args.html) and [`for` meta-variables](https://ss64.com/nt/for.html) are something completely different than [environment variables](https://ss64.com/nt/syntax-variables.html), and [delayed expansion](https://ss64.com/nt/delayedexpansion.html) only affects the latter… – aschipfl Sep 24 '21 at 13:48

2 Answers2

3

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

phuclv
  • 37,963
  • 15
  • 156
  • 475
2

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"
)
Squashman
  • 13,649
  • 5
  • 27
  • 36