Tuesday, July 21, 2009

The Windows "FOR" Loop

As some of you may or may not know windows supports numerous different kinds of FOR loops. This post aims to discuss two of the most common and powerful.

FOR /L loops can be used as counters, starting at a given number, and incrementing by a given step, counting to another number.

FOR /F loops are more advanced and offer options of iterating over a set of files, the contents of files or the output of a command.

Syntax And Usuage
The syntax for the FOR /L loop is as follows
c:\> for /L %i in ([begin],[increment],[end]) do [command]

Using the syntax above we could implement a simple counter using the following:
c:\> for /L %i in (1,1,10) do echo %i

In case you're not a programmer, %i represents a variable we wish to use as our incrementer. We can also refer to the %i in the [command] and it will be replaced with the current value through the loop. Pretty cool huh? %i will start at [begin],changing by [increment] at each cycle through the loop, and going up to [end] value. The [command] will run once during the loop.It is important to note that %i should be an integer as good ole windows will drop any decimal places.

My very first program was to print 'Hello World' to the console. Yeah I know, it's boring but hey, we all have to start some where. And so on that note let's print 'Hello World' using our loop.

c:\> for /L %i in (1,1,10) do echo Hello World
This will print Hello World to the console ten times. A sample of the output is also shown.

c:\>echo 1 Hello world
1 Hello world

c:\>echo 2 Hello world
2 Hello world

c:\>echo 3 Hello world
3 Hello world

You will notice that the output is ugly. We can clean this up, essentially turning off echo by adding the "@" in front of our [command]. Our new loop now becomes

c:\>for /L %i in (1,1,10) do @echo %i Hello world
1 Hello world
2 Hello world
3 Hello world

This looks much better. Again take note that only a sample of the output is shown here.

Ok, so we can print Hello World ten times. What good is that? Well we can extend it to build a simple ping sweep like so:

Ping Sweep
c:\> for /L %i in (1,1,255) do @ping -n 1 192.168.1.%i | find "Reply"

This command will create our counting loop with a variable of %i, starting at 1, incrementing by1, going through to 255. On each iteration it will ping without displaying the command (@), sending(-n 1) ICMP echo request message to 192.168.1.%i. And scraping through the results looking for the word "Reply" indicating a response to the ping request.

All this is nothing new. Ed Skoudis covers this and a lot more in his weekly Command Line Fu blog. I encourage you to check it out.

The next post will cover the more advanced FOR /F loop.

No comments:

Post a Comment