Loops are used to execute code block for a number of times.
Suppose you want to execute commands repeately or prins an array.for loop is used in Bash
Different types of loops
Bash script provides multiple types of loops
- for loop
- for index loop
- while loop
- until loop
for loop
for loop used to execute code multipe times based on
for element in [list]
do
## Code block
done
The example iterates the list and prints to console.
for element in 1 2 3 4 5
do
echo $element
done
for index loop
for index loop is similar to C language for index loop It executes code multiple times based on condition is true, It starts with initial value and iteration contails the value to be incremented by 1.
for (( assignment; condition; iteration )); do
# code block
done
example
for ((i=0;i<5;i++));do
echo $i
done
It prints the numbers from 0 to 5
while loop in bash
The while
loop in Bash allows for the repeated execution of code as long as a specified condition is true
. If the condition becomes false
, the loop exits.
The basic structure of a while loop is as follows:
while [ condition ]; do
# code block
done
Example:
i=0
while [[ i -lt 100 ]]; do
echo "$i"
i=$((i+1))
done
while loop executes code as long as the specified condition([[ i -lt 100 ]]
) is true.
Code block increments the value by 1 and prints the value.
if condition is false, loop exits.
Until loop in bash
The until
keyword in Bash is employed to repeatedly execute code until a specified condition becomes true
, at which point the loop exits.
The basic structure of an until loop is as follows.
until [ condition ]; do
# code block
done
until
keyword is used in Bash and ends with done
.
i=0
until [[ i -eq 100 ]];
do
echo "$i"
i=$((i+1))
done
In the example, The code block executes as long as [[ i -eq 100 ]]
is false. It increments the value by 1 and prints the value.
output prints the numbers from 0 to 99 numbers