Search⌘ K

Controlling the Loop Execution: break

Explore how to control loop execution in Bash using break and exit commands. Understand when to interrupt loops for efficient script flow and how to handle results to keep your code clear and manageable.

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 ...