This tutorial aims to provide a comprehensive understanding of controlling loops using 'break' and 'continue' statements in shell scripting. By the end of this tutorial, you will have learned:
Before you start, you should have a basic understanding of shell scripting and how loops work in programming.
The 'break' statement in shell scripting is used to terminate the execution of the entire loop, after which the control goes to the statement following the loop.
Here's an example:
for (( i=1; i<=10; i++ ))
do
if [ $i -gt 5 ]
then
break
fi
echo $i
done
In this example, the 'break' statement is used to stop the loop as soon as the variable i
is greater than 5.
The 'continue' statement is used to skip the current iteration of the loop and continue with the next iteration.
Here's an example:
for (( i=1; i<=10; i++ ))
do
if [ $i -eq 5 ]
then
continue
fi
echo $i
done
In this example, the 'continue' statement is used to skip the current iteration when i
is equal to 5.
Let's take a look at some more examples.
for (( i=1; i<=10; i++ ))
do
if [ $i -gt 5 ]
then
break
fi
echo $i
done
This script will output the numbers from 1 to 4. When i
is 5, the 'break' condition is met, and the loop is exited.
for (( i=1; i<=10; i++ ))
do
if [ $i -eq 5 ]
then
continue
fi
echo $i
done
This script will output the numbers from 1 to 10, skipping 5. When i
is 5, the 'continue' condition is met, and that iteration is skipped.
This tutorial covered the 'break' and 'continue' statements in shell scripting. 'Break' is used to exit a loop entirely, while 'continue' is used to skip the current iteration and continue with the next one. Understanding these concepts is crucial for controlling the flow of loops in your shell scripts.
for (( i=1; i<=100; i++ ))
do
if [ $i -gt 50 ]
then
break
fi
echo $i
done
for (( i=1; i<=100; i++ ))
do
if (( $i % 10 == 0 ))
then
continue
fi
echo $i
done
Continue practicing to enhance your shell scripting skills. Happy scripting!