0

I'm trying to create a menu selection with a Windows batch file.

When I use a for loop which creates variable i, and use it to call variable something[i] with !something[%%i]!, it works perfectly.

However, when I try to create variable j from user input, and use it to call variable something[j] using !something[%%j]!, it doesn't work.

I'm not sure why it's treating variable j differently to variable i, but it seems j can only be called by using !j! rather than %%j

@echo off
setlocal EnableDelayedExpansion

set something[0]=aaaa
set something[1]=bbbb
set something[2]=cccc
set something[3]=dddd
set something[4]=eeee
set something[5]=ffff
set something[6]=gggg

for /l %%i in (0,1,6) do echo %%i. !something[%%i]!

set /p j="Input selection: "
echo.
echo j=%%j
echo j=!j!
echo.
set Selection=!something[%%j]!

echo Selection = !Selection!
pause

Here is a sample output:

0. aaaa
1. bbbb
2. cccc
3. dddd
4. eeee
5. ffff
6. gggg
Input selection: 3

j=%j
j=3

Selection =
Press any key to continue . . .
Knowbody
  • 66
  • 5

2 Answers2

2

Temporary %%variables are only valid within a FOR statement. You are attempting to use %%j outside of the FOR loop. Here are 2 ways to get the desired result.

@echo off
setlocal EnableDelayedExpansion

set something[0]=aaaa
set something[1]=bbbb
set something[2]=cccc
set something[3]=dddd
set something[4]=eeee
set something[5]=ffff
set something[6]=gggg

for /l %%i in (0,1,6) do echo %%i. !something[%%i]!

set /p j="Input selection: "
echo.
echo j=%j%
echo.
set Selection=!something[%j%]!

echo Selection = %Selection%
pause
​

or

@echo off

set something[0]=aaaa
set something[1]=bbbb
set something[2]=cccc
set something[3]=dddd
set something[4]=eeee
set something[5]=ffff
set something[6]=gggg

for /l %%i in (0,1,6) do call echo %%i. %%something[%%i]%%

set /p j="Input selection: "
echo.
echo j=%j%
echo.
call set Selection=%%something[%j%]%%

echo Selection = %Selection%
pause​
RGuggisberg
  • 4,630
  • 2
  • 18
  • 27
  • Thanks, I had thought I needed to use a double "%" when calling any variable from a batch file using percent signs (the first percent sign to escape the second), and tried using !something[%%j%%]! as well. – Knowbody Feb 04 '15 at 01:39
1

You are confusing a for parameter (%%j) with a variable (%j%). The following example may make this difference clearer:

for %%j in (%j%) do set Selection=!something[%%j]!

However, in this case you may directly use:

set Selection=!something[%j%]!

You may also use this form:

call set Selection=%%something[%j%]%%

that doesn't require delayed expansion, but is slower.

However, if the set command is placed inside parentheses (i.e. in a multi-line IF or FOR command), then only certain forms may be used. Furter details on all these variations are explained in this post.

aritz331_
  • 68
  • 2
  • 9
Aacini
  • 65,180
  • 12
  • 72
  • 108