Windows – Batch File Not Looping for Non-File Items in a List

batchbatch filewindows

Within an elevated command using Windows 10, I run this batch file:

@echo off
cls
for /f "tokens=1-6 delims=," %%G in ("3D Objects,Documents,Downloads,Music,Pictures,Videos") do (
echo %%G
)

I expect it to list each of those six items. Instead, it lists only the first one (3D Objects), and then stops. Using "Tokens" doesn't seem to make much difference, and "delims" doesn't seem to be functioning as I thought it would.

Question: Am I mistaken in thinking that FOR can handle comma-delimited items in a list?

Best Answer

I don't think it is working as you expect for a non-file list because as indicated within for /?. . .

  • FOR /F ["options"] %variable IN (file-set) DO command [command-parameters]
    FOR /F ["options"] %variable IN ("string") DO command [command-parameters]
    FOR /F ["options"] %variable IN ('command') DO command [command-parameters]
    

I believe this means the FOR /F handles either command, string, or file-set which I presume file-set specifically means an actual file. If this is the case, then that means putting the non-file list within there, it's interpreted as being a string which the delims and tokens cannot parse or iterate.


To resolve put the non-file list within a regular for loop without using any tokens or delims, and ensure values which contain a space are enclosed with double quotes.

@echo off
cls
for %%G in ("3D Objects",Documents,Downloads,Music,Pictures,Videos) do (
echo %%~G
)

You could put double quotes around all values and use the [~] tilde in the variable placeholder to parse out the double quotes from the output value giving the desired output without double quotes.

@echo off
cls
for %%G in ("3D Objects","Documents","Downloads","Music","Pictures","Videos") do (
echo %%~G
)

Output

3D Objects
Documents
Downloads
Music
Pictures
Videos

Supporting Resources

Related Question