5

I'm new to batch files and I'm trying to write one to do part of my work (I know lazy right)

So far I have the following...

SET skip=1

REM for all the directories indicated to contain core repositories
FOR /F "skip=%skip% delims=" %%i IN (C:\Repos.txt) DO ( 
SET TgtDir =%%i
echo %TgtDir% >> C:\result.txt
)

The contents of Repos.txt is:

60000
C:\somedir\someotherdir\
C:\a\b\c\

Basically I want this script to go through a file, ignoring the first line which will be used for a delay setting later, and extract each line then (ideally) pass it to a cd command but for now I'm just trying to get it into the variable TgtDir.

When i run this script the output in C:\result.txt is:

ECHO is on.
ECHO is on.

Any help?

phuclv
  • 37,963
  • 15
  • 156
  • 475
Richard Newman
  • 630
  • 2
  • 7
  • 17
  • 1
    `SET TgtDir =%%i` sets a variable called `TgtDir ` - note the extra space, so `%TgtDir%` returns nothing as there's nothing called that – SeanC Sep 20 '12 at 16:54

2 Answers2

10

You'll want to look at the EnableDelayedExpansion option for batch files. From the aforementioned link:

Delayed variable expansion is often useful when working with FOR Loops. Normally, an entire FOR loop is evaluated as a single command even if it spans multiple lines of a batch script.

So your script would end up looking like this:

@echo off
setlocal enabledelayedexpansion
SET skip=1

REM for all the directories indicated to contain core repositories
FOR /F "skip=%skip% delims=" %%i IN (C:\Repos.txt) DO (
    SET TgtDir=%%i
    echo !TgtDir! >> C:\result.txt
)

As an alternative, just use the %%i variable in your inner loop, rather than creating a new variable.

Jonah Bishop
  • 12,279
  • 6
  • 49
  • 74
  • This solved my issue as well. In my case the script always failed the first time it was executed in a new cmd.exe. Running it twice in the same cmd.exe would however work. Thanks for this hint. :) – Qben Oct 05 '12 at 08:30
0
@echo off
setlocal enabledelayedexpansion
SET skip=1
REM for all the directories indicated to contain core repositories
FOR /F "skip=%skip% delims=" %%i IN (C:\Repos.txt) DO echo %%n>>c:result.txt
McDowell
  • 107,573
  • 31
  • 204
  • 267
mordex
  • 1