Simple For loop
To execute a for loop we can write the following syntax:
#!/bin/bash
for n in a b c;
do
echo $n
done
- In the first iteration,
n
takes the value “a”, and the script prints “a”. - In the second iteration,
n
takes the value “b”, and the script prints “b”. - In the third iteration,
n
takes the value “c”, and the script prints “c”.
The above command will iterate over the specified elements after the in keyword one by one. The elements can be numbers, strings, or other forms of data.
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