while
while checks a condition and, as long as it is true, runs its block. The condition is evaluated again before every iteration, so the block may run zero times.
See also: while command help and Control Flow - while in the Book.
mut x = 0
while $x < 10 { $x = $x + 1 }
$x
# => 10Language Notes
The condition is an expression that must evaluate to a
bool. A pipeline or command call needs parentheses:while ($queue | is-empty) == false { ... }.mut queue = [a b c] while not ($queue | is-empty) { print $"processing ($queue | first)" $queue = ($queue | skip 1) } # => processing a # => processing b # => processing cA non-boolean condition is a runtime error; Nushell does not convert values to "truthy" or "falsy" ones.
while 1 { break } # => Error: nu::shell::type_mismatch # => # => × Type mismatch. # => ╭─[repl_entry #1:1:7] # => 1 │ while 1 { break } # => · ┬ # => · ╰── expected bool # => ╰────If the condition is
falsefrom the start, the block never runs:mut x = 10 while $x < 3 { print "never runs" } $x # => 10Like
loop,whileevaluates tonothing, the block's values are discarded, and the block can updatemutvariables from the enclosing scope because it is a block and not a closure. For the same reason, the condition must not be written as a closure:mut x = 0; while { $x < 3 } { $x += 1 } # => Error: nu::parser::expected_keyword # => # => × Capture of mutable variable. # => ╭─[repl_entry #1:1:20] # => 1 │ mut x = 0; while { $x < 3 } { $x += 1 } # => · ─┬ # => · ╰── capture of mutable variable # => ╰────breakandcontinuework inwhilejust as inloopandfor.while true { ... }is equivalent toloop { ... }:mut i = 0 while true { $i += 1 if $i == 2 { continue } if $i > 4 { break } print $i } # => 1 # => 3 # => 4whiledoes not accept pipeline input. To iterate over a list or table, useforor a filter such aseach. To consume a list only while a condition holds,take whileis usually simpler than awhileloop:[1 3 5 6 7] | take while {|n| $n mod 2 == 1 } # => ╭───┬───╮ # => │ 0 │ 1 │ # => │ 1 │ 3 │ # => │ 2 │ 5 │ # => ╰───┴───╯