Lecture # 5 - Repetitive Structure in Shell Script
for Loop, while Loop, break and continue.
Repetitive Structure in Shell Script:
In shell scripting, repetitive structures such as loops are used to execute a block of code multiple times, typically based on certain conditions or a predefined number of iterations. The two most commonly used types of loops in shell scripting are the for
loop and the while
loop.
for Loop:
The for
loop is used to iterate over a list of items, such as a sequence of numbers, filenames, or elements of an array. Its syntax is:
for variable in list
do
# Commands to be executed for each iteration
done
while Loop:
The while
loop is used to execute a block of code repeatedly as long as a specified condition is true. Its syntax is:
while [ condition ]
do
# Commands to be executed repeatedly
done
break Statement:
Within loops, you can use the break
statement to exit the loop prematurely.
continue Statement:
Within loops, you can use the continue
statement to skip the current iteration and proceed to the next iteration.