LinuxCommandLibrary
GitHubF-DroidGoogle Play Store

break

Exit from a loop in shell scripts

TLDR

Break from loop
$ break
copy
Break multiple levels
$ break [2]
copy

SYNOPSIS

break [n]

DESCRIPTION

break is a bash built-in command that exits from a for, while, or until loop. It can optionally break out of multiple nested loops by specifying the number of levels.The command is essential for loop control in shell scripts.

PARAMETERS

n

Number of loop levels to break (default: 1)

WORKFLOW

$ # Break from single loop
for i in {1..10}; do
  if [ $i -eq 5 ]; then
    break
  fi
  echo $i
done

# Break from nested loops
for i in {1..3}; do
  for j in {1..3}; do
    if [ $j -eq 2 ]; then
      break 2  # Break both loops
    fi
    echo "$i $j"
  done
done

# Break from while loop
while read line; do
  if [ "$line" = "END" ]; then
    break
  fi
  process "$line"
done < file.txt
copy

CAVEATS

Only works within loops (for, while, until). Breaking more levels than exist exits all loops. Not the same as exit (which exits entire script). Continue skips to next iteration instead of exiting.

HISTORY

break has been a standard shell built-in command since the Bourne shell in the late 1970s.

SEE ALSO

continue(1), exit(1)

Braincup
Open source brain training for math, memory and focus
Braincup mini-games
41 mini-games · Apache-2.0
No ads · No tracking
Play in browser
Download Braincup on the App StoreGet Braincup on Google PlayGet Braincup on F-Droid
276 stars
From the maker of Linux Command Library
Copied to clipboard
Braincup
Open source brain training for math, memory and focus. 41 mini-games, from mental arithmetic to Sudoku, N-Back and Solo Chess.
Apache-2.0 licensed · No ads · No tracking · No account
From the maker of Linux Command Library
Download Braincup on the App StoreGet Braincup on Google PlayGet Braincup on F-Droid