for Loop in Bash - For a programmer, it might necessitate to run a particular block of code a few or many times, repeatedly. To achieve this, we can use of Loop Statements. In bash, there are two types of loops -
for
loop and while
loop. In this article, we will be discussing the former one, see multiple ways of creating a loop along with its examples. Here we go!
Bash for
Loop
A
for
loop can be created with three components - Initialization, Control Condition, Iteration. With initialization, we initialize a variable to begin the loop. The control condition decides how long the loop will run for. As long as the condition is True, the loop will goon executing and stop as soon as condition becomes False. The iteration controls the variable initialized, by incrementing/decrementing it. So, we can put down the syntax of a for
loop as:Syntax:
for ((Initialization; Control Condition; Iteration)) do -- Block of Commands -- done
Example:
#!/bin/bash for (( i=1; i<=5; i++ )) do echo "This is Iteration No. $i" done
In the above code,
i=1;
is the Initialization part, in which we have initialized value of the loop variable i
to 1
. As long as the condition i<=5;
is True, the loop will continue to run. Now that, if we do not increment the value of our loop variable, the loop will never end. So, its value must be updated after every iteration. Hence the last statement - i++
(a shorthand to i = i + 1
in other programming languages).
So, for iteration 1,
i=1
which is also <=5
, so echo
statement will execute. Here, iteration 1 completes and value of i
is incremented by 1, which means, i=2
. This also follows the condition, hence echo
command is executed. This will go on till i=5
. At this point, after the code inside is executed, it's value is incremented, meaning now i=6
, which doesn't follow the condition and the loop terminates.Result:
This is Iteration No. 1 This is Iteration No. 2 This is Iteration No. 3 This is Iteration No. 4 This is Iteration No. 5
An Infinite Loop
If we do not mention any condition in the parenthesis, the loop will run forever, hence termed as Infinite Loop. Thus, it is very important to mention all the three statements inside parenthesis to avoid such state, or the subsequent code after the infinite
for
loop will never execute and your program will never exit. While, you can create an infinite for
loop on the terminal as below and in order to exit from it, press Ctrl + C
.Example:
#!/bin/bash for (( ; ; )) do echo "You are in an Infinite Loop. Press CTRL + C to Exit.." done
For Loop with Numeric Ranges
With
for .. in
combination, we can iterate through a sequence. At each iteration, the loop variable takes the value of each item in the sequence, which then can be operated on in the block of code.Syntax:
for VAR in 1 2 3 .. N do -- Block of Commands -- done
Example:
for i in 1 2 3 4 5 do echo "You are in Loop No. $i" done
Result:
You are in Loop No. 1 You are in Loop No. 2 You are in Loop No. 3 You are in Loop No. 4 You are in Loop No. 5
Instead of writing the whole series of numbers, you can also specify the range in the
{START..END}
format (END
Inclusive). The variable will iterate through this range of numbers with a step value of 1 and the for
loop will execute the block of commands for every number in the specified range.Syntax:
for VAR in {START..END} do -- Block of Commands -- done
Example:
for i in {1..5} do echo "You are in Loop No. $i" done
Result:
You are in Loop No. 1 You are in Loop No. 2 You are in Loop No. 3 You are in Loop No. 4 You are in Loop No. 5
In the above example, the variable value increments by 1, by default, after each iteration. You can also specify the step count as
{START..END..STEP}
, which denotes how many elements to skip.Example:
for i in {0..15..3} do echo "You are in Loop No. $i" done
Result:
You are in Loop No. 0 You are in Loop No. 3 You are in Loop No. 6 You are in Loop No. 9 You are in Loop No. 12 You are in Loop No. 15
Using seq
Command
The
seq
command is used to generate a sequence of numbers, as we just did in above example. seq
command does the same for us, with similar syntax.
'seq' Syntax:
seq END seq START END seq START INC END
Let us now create a
for
loop using seq
command.Example:
#!/bin/bash for i in $(seq 0 3 15) do echo "You are in Loop No. $i" done
Result:
You are in Loop No. 0 You are in Loop No. 3 You are in Loop No. 6 You are in Loop No. 9 You are in Loop No. 12 You are in Loop No. 15
'Break'ing the Loop
The
break
statements are used in for
, while
and until
loops to prematurely exit from the loop. Normally, these statements are used with some condition, so that, the loop is terminated when the condition is satisfied. Check our article on Bash Conditionals for more details.Syntax:
for VAR in {RANGE} do -- Some Commands -- if [ condition ] then break fi -- More commands -- done
As an example, we would look for a file
/etc/init.d/networking
in its parent directory if it exists. We iterate through the files in the directory /etc/init.d
. As soon as we find a file with name networking
, we print Found!
and break out from the loop.#!/bin/bash for file in /etc/init.d/* do if [ "$file" == "/etc/init.d/networking" ] then echo "Found!" break fi done echo "Search Complete!"
The above script will go through each and every file in the /etc/init.d directory. As soon as it finds 'networking' file therein, it will print 'Found!' and exit from the loop.
The 'continue' Statement
The
continue
statement in a loop, when certain condition satisfies, skips all the subsequent statements from executing and continues with the next iteration of the loop.Syntax:
for VAR in {RANGE} do -- Some Commands -- if [ condition ] then continue fi -- More commands -- done
Example:
for i in {1..20} do j=$(expr $i % 2) if [ $j == 0 ] then continue fi echo "$i" done
In above code, we iterate through the numbers from 1 to 20. We check whether a number is completely divisible by 2 (to check if it's even - please read our article on Bash Arithmetic Operations for more details). If it is,
continue
statement is executed and the control goes to the beginning of the loop, to start next iteration, thus skipping the execution of echo
statement. When a number is odd, condition becomes False, continue
statement does not execute and echo
statement print the number out. In the end, we get all odd numbers on the terminal screen.Result:
1 3 5 7 9 11 13 15 17 19
Thus, we close our discussion on
for
loops. We learned to create for
loops using the generic method. We also used for
loops to iterate through a sequence of numbers. We also learned to use break
and continue
statements to break the loop prematurely and skip executing of subsequent code, respectively. We will revisit them when we see another kinds of loops in the further articles. Please share your views and feedback in the comment section below and stay tuned. Thanks.
0 comments:
Post a comment