Free Hosting Online for WorkStations

< Previous | Contents | Next >

for: C Language Form

Recent versions of bash have added a second form of for command syntax, one that resembles the form found in the C programming language. Many other languages support this form, as well:

for (( expression1; expression2; expression3 )); do

commands

done

where expression1, expression2, and expression3 are arithmetic expressions and com- mands are the commands to be performed during each iteration of the loop.

In terms of behavior, this form is equivalent to the following construct:

(( expression1 ))

while (( expression2 )); do

commands

(( expression3 ))

done

expression1 is used to initialize conditions for the loop, expression2 is used to determine when the loop is finished, and expression3 is carried out at the end of each iteration of the loop.

Here is a typical application:



#!/bin/bash

# simple_counter: demo of C style for command for (( i=0; i<5; i=i+1 )); do

echo $i done

#!/bin/bash

# simple_counter: demo of C style for command for (( i=0; i<5; i=i+1 )); do

echo $i done

for: C Language Form


When executed, it produces the following output:



[me@linuxbox ~]$ simple_counter

0

1

2

3

4

[me@linuxbox ~]$ simple_counter

0

1

2

3

4


In this example, expression1 initializes the variable i with the value of zero, expression2 allows the loop to continue as long as the value of i remains less than 5, and expression3 increments the value of i by one each time the loop repeats.

The C language form of for is useful anytime a numeric sequence is needed. We will see several applications for this in the next two chapters.


Top OS Cloud Computing at OnWorks: