break
break stops the innermost enclosing loop immediately. Execution continues with the first statement after that loop.
See also: break command help and Control Flow - break in the Book.
for x in 1..10 { if $x > 3 { break }; print $x }
# => 1
# => 2
# => 3Language Notes
breakworks only insidefor,whileandloop. Using it anywhere else is a compile error. This includes closures such as the ones passed toeach,whereordo, even when that closure is itself inside a loop, because a closure is a separate function:[1 2 3] | each {|x| if $x == 2 { break }; $x } # => Error: nu::compile::not_in_a_loop # => # => × 'break' can only be used inside a loop # => ╭─[repl_entry #1:1:34] # => 1 │ [1 2 3] | each {|x| if $x == 2 { break }; $x } # => · ──┬── # => · ╰── can't be used outside of a loop # => ╰────for x in 1..3 { do { break } } # => Error: nu::compile::not_in_a_loop # => # => × 'break' can only be used inside a loop # => ╭─[repl_entry #1:1:22] # => 1 │ for x in 1..3 { do { break } } # => · ──┬── # => · ╰── can't be used outside of a loop # => ╰────Blocks that are not closures, such as the branches of
ifandmatchand the body oftry, are fine.To stop a stream early without a loop, use
take whileortake untilinstead:[1 2 3 4 5 6] | take while {|x| $x <= 3 } # => ╭───┬───╮ # => │ 0 │ 1 │ # => │ 1 │ 2 │ # => │ 2 │ 3 │ # => ╰───┴───╯breaktakes no arguments. Loops always evaluate tonothing, so there is no value to pass out. Assign to amutvariable before breaking, or usereturninside a custom command.for x in [1 2] { break 5 } # => Error: nu::parser::extra_positional # => # => × Extra positional argument. # => ╭─[repl_entry #1:1:24] # => 1 │ for x in [1 2] { break 5 } # => · ┬ # => · ╰── extra positional argument # => ╰──── # => help: Usage: breakIn nested loops,
breakleaves only the innermost loop. There are no loop labels:for i in 1..3 { for j in 1..3 { if $j == 2 { break }; print $"($i),($j)" } } # => 1,1 # => 2,1 # => 3,1A
finallyblock of a surroundingtrystill runs whenbreakjumps out of it:for i in 1..3 { try { break } finally { print "cleanup" } }; print done # => cleanup # => done