Search code examples
for-loopenvironment-variablescommand-promptsetenvstring-building

Building an Evironment Variable with SET using a FOR loop in Command Prompt


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.


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%