Controlling the Loop Execution: break

Learn how we can control the execution of the loop using break.

We'll cover the following

Controlling the loop execution

The loop condition dictates when it should run and stop. Two Bash built-ins can change this behavior. Using them, we can interrupt the loop or skip its iteration. Let’s consider these built-ins in detail.

break

The break built-in stops the loop immediately. It is useful for handling an error and finishing an infinite loop.

Here is an example of using break. Let’s suppose we write a script that searches the specific array element by its value. We apply the loop to traverse the array. When we find the element, there is no reason to continue the loop so we can finish it immediately with the break command. The for-break.sh shows how to do it.

Get hands-on with 1200+ tech skills courses.