For Statement: The First Form of For
Learn about the for statement in detail.
We'll cover the following
For statement
There is another loop statement in Bash called **for**
. We should use for
when we know the number of iterations we need in advance.
The for
statement has two forms. The first one processes words in a string sequentially. The second form applies an arithmetic expression in the loop condition.
The first form of for
Let’s start with the first form of the for
statement. It looks like this in the general form:
for VARIABLE in STRING
do
ACTION
done
We can write the same construction in a single line like this:
for VARIABLE in STRING; do ACTION; done
The ACTION
of the for
statement is a single command or a block of commands. It is the same thing as the one in the while
statement.
Bash performs all expansions in the for
condition before starting the first iteration of the loop. What does it mean? Let’s suppose we specified the command instead of the STRING
. Then, Bash executes this command and replaces it with its output. Also, we can specify a pattern instead of the STRING
. Then, Bash expands it before starting the loop.
Bash splits the STRING
into words when there are no commands or patterns left in the for
condition. It takes the separators for splitting from the IFS
variable.
Then, Bash executes the first iteration of the loop. The first word of the STRING
is available via the VARIABLE
inside the loop body on the first iteration. Then, Bash writes the second word of the STRING
to the VARIABLE
and starts the second iteration. This continues until we handle all words of the STRING
.
Here is an example of the for
loop. Let’s suppose that we need a script that prints words of a string one by one. The script receives the string via the first parameter. for-string.sh
shows what its code looks like.
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.
Get hands-on with 1200+ tech skills courses.