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

Get Bash Quick Start Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.