...

/

For Statement: The Second Form of For

For Statement: The Second Form of For

Learn the second form of the for statement and cases when we need it.

The second form of for

The second form of the for statement allows us to apply an arithmetic expression as a condition. Let’s consider cases when we need the second form.

Let’s suppose that we write a script for calculating a factorial. The solution for this task depends on the way we enter the data. The first option is that we have a predefined integer. Then, we can apply the first form of the for loop. The for-factorial-brace.sh shows this solution.

Let’s click on the “Run” button and then execute the file. If we made any changes in the file, click on the “Run” button again before executing the file.

#!/bin/bash

result=1

for i in {1..5}
do
    ((result *= $i))
done

echo "The factorial of 5 is $result"
Applying the second form of For

The second option is that the script gets an integer via the parameter. We can try to keep the first form of for and handle the $1 parameter like this:

for i in {1..$1}

We can expect that Bash does brace expansion here. However, it does not =.

The brace expansion happens before the parameter expansion. Thus, the loop condition gets the “{1…$1}” string instead of “1 2 3 4 5.” Bash does not recognize the brace expansion here because the upper bound of the ...