Question

I am having trouble with the following command prompt commands (in Windows XP).

    set SOMEVAR=
    for /F %i in (1 2 3) do set SOMEVAR=%SOMEVAR% "%i"
    echo %SOMEVAR%

I expect it to build the SOMEVAR variable so that it contains each item in the for loop in quotes, separated by a space:  1 2 3

However what this is what I get instead.

  >    set SOMEVAR=
  >    for /F %i in (1 2 3) do set SOMEVAR=%SOMEVAR% "%i"
  >set SOMEVAR=%SOMEVAR% "1"
  >set SOMEVAR=%SOMEVAR% "2"
  >set SOMEVAR=%SOMEVAR% "3"
  >    echo %SOMEVAR%
  %SOMEVAR% "3"

It looks like environment variables are not updated and/or expanded during a FOR loop.

Any ideas how to build an environment variable with a FOR loop?

A workaround that I’m currently using is to have the FOR loop call a local label in the BAT file which SETs the variable to itself plus %1, then jumps to :EOF. It works, but I’d like to figure out if there is a way to get it to work in one line without the call and label overhead.

Was it helpful?

Solution

its an option you have to enable

> help for

will explain

oops, i meant

> help set

be sure to read all the way to the bottom

Edit: it turns out that you can turn this on in an individual a batch file. save this text as temp.bat

SETLOCAL ENABLEEXTENSIONS
SETLOCAL ENABLEDELAYEDEXPANSION
set SOMEVAR=
for %%i IN (temp.*) DO set SOMEVAR=!SOMEVAR! "%%i"
echo %SOMEVAR%

OTHER TIPS

here's an equivalent alternative, using vbscript which is already on your system

somevar=""
For i=1 To 3 
    somevar=somevar & i
Next
WScript.Echo somevar

output

C:\test>cscript //nologo test.vbs 123

Plus, if you are going to use a lot of these stuff, you can make use of vbscript's dictionary collection or arrays to store your variables.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top