Range-based for loop
We can use range-based for loops. In this type of loop, we can specify the number to start, to stop, and to increment at every iteration(optional) in the statement. There are two ways you can do this i.e. by mentioning the increment/decrementer value and by incrementing by one by default. The syntax looks like this:
#!/bin/bash
for n in {1..5};
do
echo $n
done
In the above code, we use the “{}” to specify a range of numbers. Inside the curly braces, we specify the start point followed by two dots and an endpoint. By default, it increments by one. Hence we print 5 numbers from 1 to 5 both inclusive.
#!/bin/bash
for n in {1..5..2};
do
echo $n
done
Here we can see that the loop incremented by 2 units as mentioned in the curly braces. Thus, this makes working with numbers very easy and convenient. This can also be used with alphabetical characters.
NOTE: We cannot use variables inside the curly braces, so we will have to hardcode the values. To use the variables, we see the traditional C-styled for loops in the next few sections.
Bash Scripting – For Loop
Since BASH is a command-line language, we get some pretty feature-rich experience to leverage the programming skills to perform tasks in the terminal. We can use loops and conditional statements in BASH scripts to perform some repetitive and tricky problems in a simple programmatic way. In this article, we are going to focus on the for loop in BASH scripts.
Depending on the use case and the problem it is trying to automate, there are a couple of ways to use loops.
- Simple For loop
- Range-based for loop
- Array iteration for loops
- C-Styled for loops
- Infinite for loop