How to Write While Loop in Bash Programming
Author - Sanjay
Introduction
Bash while loop is one of the most important loops that we use in bash programming . As most of you are aware loops are basically used to perform a repetitive task And helps in controlling the execution order.
Today we are going to understand how can we write a while loop in Bash programming language along with few examples
Table of Contents
While loop Syntax
The while loop always takes the following syntax :
while [ condition ];
do
command1
command2
...
done
Now if you see in the first line the condition is basically should be a Boolean true or false. If the condition returns a Boolean true we will go inside the do statement. we will execute various commands inside the loop so my loop starts from a condition and it goes on with n number of commands we can have lot of commands between do and done statements . Now the commands between do and done will be executed until the condition in the first-line becomes false. we can think it till the condition is true to the commands between do and done will be executed n number of times.
Bash While Loop Examples
Print a Number from 1 to 10 Using While Looop
num=1
while [ $num -le 100 ]
do
echo $num
num=$(($num+1))
done
How to Create Infinite Loop using While Loop in Bash Programming
while :
do
echo "Its a While Loop."
echo "Please Press Control+C to Quit Forecefully"
sleep 1
done