As a Linux user, you must be familiar with loops and conditional statements. The break
command is one of the most important commands to master if you want to manipulate these structures efficiently.
What is the Linux Break Command?
The break
command is used in the context of loops and conditional statements. It is used to exit a loop prematurely or skip to the next iteration. It also works with nested loops.
For example, consider the following for
loop that prints the first 5 numbers:
for i in {1..10}; do
if [ $i -eq 6 ]; then
break
fi
echo $i
done
The break
command, in this case, will exit the loop when i
becomes 6. So, the output will be:
1
2
3
4
5
Use-Cases for Break Command
Breaking out of a loop based on a condition:
for i in {1..10}; do
if [ $i -eq 6 ]; then
break
fi
echo $i
done
Breaking out of a while
loop:
counter=0
while [ $counter -lt 10 ]; do
echo $counter
counter=$((counter + 1))
if [ $counter -eq 5 ]; then
break
fi
done
Breaking out of a loop when a command fails:
for file in /etc/*; do
if ! [ -r $file ]; then
echo "Can't read file: $file"
break
fi
echo "File: $file"
done
Breaking out of a nested loop:
for i in {1..3}; do
for j in {1..3}; do
if [ $i -eq 2 ] && [ $j -eq 2 ]; then
break 2
fi
echo "i: $i, j: $j"
done
done
5 Tips for Using the Linux Break Command
- Always use
break
in the context of a loop or conditional statement. break
only works within the current loop. If you want to break out of a nested loop, use thebreak N
syntax, whereN
is the number of loops to break out of.- Be careful when using
break
in scripts, as it can cause unintended consequences. - Make sure to properly indent your code to make it easier to read and understand.
- Always test your code thoroughly before deploying it in a production environment.
Key Points
- The
break
command is used to exit a loop prematurely or skip to the next iteration. - It works with both
for
andwhile
loops, as well as nested loops. break
can be used in conjunction with conditions to exit a loop based on specific criteria.- Always be mindful of the context in which
break
is used and test your code thoroughly.
Recommended Topics to Read
Next, you can read about the continue
command, which is similar to the break
command but instead of exiting a loop, it skips to the next iteration. This command is also useful for manipulating loops and conditional statements.
Challenge
Try writing a script that loops through the numbers 1 to 10, and for each number, check if it’s even. If it’s even, print “Even number: $number”. If it’s odd, use the continue
command to skip to the next iteration.
Good luck!