开发者

Why does "for" not work inside batch file? (Works fine outside)

for /F "tokens=*" %* in (Test.txt) do md ".\%*" & cd "%*" & md "Something1" & md "Something2" & cd ".."

The DOS command will pull names from text file and create a named folder then two subfolders.

A开发者_如何学Cpple

-Something1

-Something2

But when I put it into a batch file as follows:

@ECHO OFF
@for /F "tokens=*" %* in (Test.txt) do md ".\%*" & cd "%*" & md "Something1" & md "Something2" & cd ".."
ECHO Done
PAUSE

Then run it from Windows GUI a sreen pops up, closes, and does nothing. Even if I create a batch with the working DOS command it does nothing. What am I missing?

Thank you.


In batch files, you need to double the '%' in the for variable. Don't ask me why. :)


This variation works for me:

setlocal enabledelayedexpansion
for /F "tokens=*" %%g in ('type foo.txt') do (
                md ".\%%g"
                cd "%%g"
                md "Something1"
                md "Something2"
                cd ".."
        )
endlocal

I chose to put the series of commands between parentheses and one on a line. Your chain of &-separated commands should work as well.

The setlocal/endlocal block limits the scope of variables. The enabledelayedexpansion argument enables some extra features in cmd. It isn't normally needed because it's the default for CMD, but that default might have been changed via policy, so it's a good practice to include it.

I prefer using pushd / popd over cd blah / cd .. in scripts. I think it's more robust.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜