In this tutorial, we’ll explore the concept of loops in the Linux Bash scripting. Loops are control structures that allow you to repeatedly execute a block of code until a certain condition is met.
Usage of Loops
Loops are commonly used in shell scripting for various purposes, such as:
- Iterating over files and directories and moving certain files
- Processing lines from a file or input stream. For example, reading each line and appending some text.
- Executing commands until a certain condition is met.
- Performing repetitive tasks with different inputs.
There are three types of loops commonly used in Bash.
1. For Loop
The for loop allows you to iterate over a sequence of values and execute a block of code for each value.
1for variable in value1 value2 ... valuen
2do
3 # Code statements
4done
For example, let’s use a for loop to print the numbers from 1 to 5:
1#!/bin/bash
2for i in 1 2 3 4 5
3do
4 echo $i
5done
If we have to iterate over many times, writing those many numbers as sequence is cumbersome. In such conditions, we can uses braces operator like this.
1#!/bin/bash
2for i in {1..20}
3do
4 echo "Number: $i"
5done
Output:
bash script.sh
Number: 1
Number: 2
... ...
Number: 20
Looping over Array
Similar to this we can iterate over array elements using ${array_name[*]} syntax.
1names=(John Jenny Zoe)
2for name in ${names[*]}
3do
4 echo "Name: $name"
5done
Output:
Name: John
Name: Jenny
Name: Zoe
Looping through lines of a file
Similarly, for reading file content, we can use for loop along with cat command. We will see more examples of this in upcoming lesson.
1for line in `cat /path/to/file`
2do
3 echo $line
4done
2. While Loop
The while loop executes a block of code as long as a given condition is true.
1while [ condition ]
2do
3 # Statements
4done
Here’s an example that uses a while loop to count down from 5 until 0.
Example:
1#!/bin/bash
2counter=5
3
4while [ $counter -gt 0 ]
5do
6 echo $counter
7 ((counter--))
8done
3. Until Loop
Similar to the while loop, the until loop also executes a block of code repeatedly until a given condition becomes true.
1until [ condition ]
2do
3 # Statements
4done
Below is an example where we use an until loop to print numbers from 1 to 3:
1#!/bin/bash
2number=1
3
4until [ $number -gt 3 ]
5do
6 echo $number
7 ((number++))
8done
Output:
1
2
3
Loops are an essential constructs in Linux Bash scripting that allow you to automate repetitive tasks and iterate over sequences of values.


Comments