Ending the loop

The break keyword anywhere within the for loop stops the loop processing, and resumes execution at the first command after the loop's done keyword. It doesn't just skip the rest of the current iterations; it stops the current one too.

For example, the following code loops through the arguments given to the script or function, and adds each one to an opts array if it starts with a dash, -, such as -l or --help:

#!/bin/bash
opts=()
for arg ; do
    case $arg in
        -*) opts+=($arg) ;;
    esac
done

If we want to add support for the -- option termination string, to allow the user a way to specify where the options finish, we could add a case with break, like so:

case $arg in
    --) break ;;
    -*) opts+=($arg) ;;
esac

With this added, when the loop encounters the exact string -- (two characters) as an argument, it will stop processing; the rest of the arguments will not be checked, even if they do begin with a dash.

We sometimes refer to the use of continue and break statements as short-circuiting a loop.