Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does "FOR" work in cmd batch file?

Tags:

I've been programming in dozens of languages for 20 years but I could never understand how "FOR" work in windows cmd shell batch file, no matter how hard I tried. I read

http://www.amazon.com/Windows-Administration-Command-Line-Vista/dp/0470046163/ref=sr_1_1?ie=UTF8&s=books&qid=1241362727&sr=8-1

http://www.ss64.com/nt/for.html

and several other articles on the internet but still confuse and cannot accomplish anything.

Can anybody give me a concise explaination on how "FOR" works in general ?

For a little more specific question, how can I iterate through each path in %PATH% variable ? I've tried with

rem showpathenv.bat for /f "delims=;" %%g in ("%PATH%") do echo %%g 

That'd show only the first path, not all of them. Why ? What I do wrong ?

like image 363
Sake Avatar asked May 03 '09 15:05

Sake


People also ask

How do you run a loop in CMD?

FOR /D - Loop through several folders. FOR /L - Loop through a range of numbers. FOR /F - Loop through items in a text file. FOR /F - Loop through the output of a command.

What does 2 mean in batch file?

There is no meaning of :2 , as the whole construct is meaningless. (yes, it executes, but it just sets a variable (name given by the first parameter to the batch file) to nothing.

What does && do in batch file?

&& runs the second command on the line when the first command comes back successfully (i.e. errorlevel == 0 ). The opposite of && is || , which runs the second command when the first command is unsuccessful (i.e. errorlevel != 0 ).

What does * * mean in CMD?

In this case, we used the * wildcard to mean "all files in the current directory". This command prints the line containing the given string, and if there's more than one file in the list, the name of the file where it was found.


1 Answers

None of the answers actually work. I've managed to find the solution myself. This is a bit hackish, but it solve the problem for me:

echo off setlocal enableextensions setlocal enabledelayedexpansion set MAX_TRIES=100 set P=%PATH% for /L %%a in (1, 1, %MAX_TRIES%) do (   for /F "delims=;" %%g in ("!P!") do (     echo %%g     set P=!P:%%g;=!     if "!P!" == "%%g" goto :eof   ) ) 

Oh ! I hate batch file programming !!

Updated

Mark's solution is simpler but it won't work with path containing whitespace. This is a little-modified version of Mark's solution

echo off setlocal enabledelayedexpansion set NonBlankPath=%PATH: =#% set TabbedPath=%NonBlankPath:;= % for %%g in (%TabbedPath%) do (   set GG=%%g   echo !GG:#= ! ) 
like image 88
Sake Avatar answered Sep 23 '22 20:09

Sake