Monday, October 6, 2008

For and While Loops

If you are doing any sort of command line operations or you're interested in starting scripting, the best way to go about this is to start with the for loop.

Also as far as any system administration is concerned this should be an important piece of your toolkit.

So for this one we are going to show you some basic but very powerful commands.

To start, here's the basic For Loop syntax:

for i in "list";

do some_command


Or as a one-liner:

for i in "list"; do some_command; done

Basically we're taking whatever is in our "list" and looping through them one by one.

For example, below we simply count to five and in the second example we have a list of servers and we're echoing the output.

for i in $(seq 5); do echo $i ; done

for i in "server1 server server3"; do echo $i ; done

So imagine you have a hundred servers and you need to run a command on all of them - this is a very convenient way to save you lots of time by running a loop to ssh into all of them (assuming you have the proper ssh keys installed).

Another great scripting construct is the while loop. This is a very convenient way to execute some sort of command until a condition changes.

What I generally use it for is as a very convenient way to do something repetitively forever:

For example:

while [ 1 ]; do uptime; sleep 5; done

or to process a file using the read command:

while read line;do echo $line;done < myfancyfile.txt

1 comment:

Eric said...

Cool. I like the 'read' command.