-2

I'm trying to use the command: "set n=0" "for /f %%i in ('dir /a:d /b') do (set /a n+= 1) & (set var%n%=%%i)" - It always sets %%i into var0, but i can see that "set n+= 1" is working. How can i use "n" to create a different variable for each turn?

Like: var1,var2,var3.. for each folder in the directory.

Regardless of the answer, i need 'n' to hold the number of times the command ran(so the program will know the amount of folders)(Edit: Yes i know my example provides this, i was meaning if anyone changed the code, that 'n' still needed to be set to the number of runs)

Edit: I have reviewed the page: Arrays, linked lists and other data structures in cmd.exe (batch) script And found it usefull, but i don't really understand the proper usage. Could someone please help me by either fixing my code to work with DelayedExpansion or better explaining how to implement it?

Edit: Guys! This i NOT a duplicate. I tried to use DelayedExpansion and couldn't get it to work. My problem was cause by my text editor i was using (NotePad++) that is why i thought i was using DelayedExpansion wrong and was asking for clarification. I ended up fixing it myself after the answer below proved that my code WAS correct.

Community
  • 1
  • 1
  • 3
    If I had a nickel for every time somebody needed to use [delayed expansion](http://stackoverflow.com/a/30284028/4158862), I could retire. – SomethingDark May 12 '16 at 00:25
  • 5
    See: http://stackoverflow.com/questions/10166386/arrays-linked-lists-and-other-data-structures-in-cmd-exe-batch-script/10167990#10167990 – Aacini May 12 '16 at 00:42
  • `n` does hold the correct number of runs - put `echo %n%` after the `for` loop and you will see... – aschipfl May 12 '16 at 00:42

1 Answers1

1

When you create or update a variable inside of a set of parentheses, you need to use delayed expansion and refer to the variable with !variable! instead of %variable%.

As Stephan said in his answer, this is because the cmd interpreter parses an entire code block (everything inside a set of parentheses) at once and replaces variables with their values at parse time, while variables referenced with the delayed expansion method are evaluated at runtime.

@echo off
setlocal enabledelayedexpansion
cls

:: Initialize n to 0
set "n=0"

:: Use delayed expansion to create an array of
:: directories in the current directory
for /f "delims=" %%i in ('dir /a:d /b') do (
    set /a n+=1
    set var!n!=%%i
)

:: Display the list of all var_ found
set var

pause
Community
  • 1
  • 1
SomethingDark
  • 13,229
  • 5
  • 50
  • 55