How To Write Loops In Bash Programming? - Shell Scripting



Looping is a very important concept in any programming language. In this post, we will discuss how to write looping statements in Bash.

While Loop In Bash is very easy. The concept of while loop is that it will keep executing its block until the specified condition becomes false.

In our previous posts, we have seen how to specify conditions in Bash. We use the test command or [ ] and use flags as per our requirement. If you are not aware of how to use test command for specifying conditions click here to read this post first.

while loop in bash

A simple while loop syntax for Bash is given below:

while condition
do
    statement 1
    statement 2
done

Let's write a simple script to demonstrate while loop:

#!/bin/bash
a=1
b=10
while [ $a -lt $b ]
do
    echo "The value of a is $a"
    $a=$((a+1))
done

Output

The value of a is 1
The value of a is 2
The value of a is 3
The value of a is 4
The value of a is 5
The value of a is 6
The value of a is 7
The value of a is 8
The value of a is 9

For Loop In Bash

Look at a basic script of a for loop:

#!/bin/bash
for i in {1..10}
do
    echo "The value of i is $i"
done

This looks something like for loop in python right? But, what's the {1..10}?
In Bash, you can create iterable sequence like this only. The above program print values from 1 to 10.

If you write {1..100}, then it will go from 1 to 100. Similarly, you can give a step value. just write
{1..10..2}

Look At the below program:

#!/bin/bash
for i in {1..10..2}
do
    echo "The value of i is $i"
done

Output

The value of i is 1
The value of i is 3
The value of i is 5
The value of i is 7
The value of i is 9
We can also use the conventional C and c++ method of for loop, Look at the below code:

#!/bin/bash

for ((i=0; i<=10; i++))
do
    echo "The value of i is $i"
done
Output
The value of i is 0
The value of i is 1
The value of i is 2
The value of i is 3
The value of i is 4
The value of i is 5
The value of i is 6
The value of i is 7
The value of i is 8
The value of i is 9
The value of i is 10

The for loop can be used in various ways in Bash! One more interesting way of using for loop is:

#!/bin/bash
for i in 1 2 3 4 5 6 7
do
    echo $i
done

Output

1
2
3
4
5
6
7
Finally, we have covered everything needed for start loops in Bash. All the things we discussed are very important and act as a piece of foundational knowledge for writing Bash script.\

If you like this post, follow, share, and subscribe. Show your support to our Blog.

For now, Peace out
Thank you.

Post a Comment

0 Comments