While Loops in Bash Scripting | 2022

 While Loops in Bash Scripting | 2022

While Loops in Bash Scripting | 2022

What are Loops? 

Loop is a sequence of instructions that is continually repeated until a certain condition is reached.

Why do we need Loops? 

Loops in computer programming are so important that they can perform tasks within seconds while reducing, to a great extent, the time and effort of the users.

What is a While loop?

A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement.

The syntax for While Loop:- 


while [ condition ]
do
command 1
command 2
.
.
.
command n
done


While Loops in Bash Scripting | 2022

Using While Loop

  1. Outputting a range of numbers. 

#!/bin/bash

n=1

echo "Getting in the loop"

while [ $n -le 10 ]
do
echo "$n"
((
n++))
done

echo "Out of the loop"


The above is the demonstration of a simple While loop which is just printing the numbers from 1 to 10. 


$ bash bashscript.sh


While Loops in Bash Scripting | 2022

We just initialized a variable n with 1, and we ran a loop giving it the condition that runs till the variable n is less than or equal to 10, we then printed the n & incremented the n otherwise the loop will never end and goes in Infinitive state.

You can now do some questions related to while loops, you can use some Conditional statements in loops to make them more usable. 

Conclusion:- 

  1. Learned what are loops.

  2. Learned why we need loops 

  3. Learned what are while loops 

  4. The syntax for while loops 

  5. An example demonstrating a while loop 











Next Post Previous Post
No Comment
Add Comment
comment url