for
for runs a block once for each item of a list, table, range or stream, with the item bound to a loop variable.
for <variable> in <value> { <block> }See also: for command help and Control Flow - for in the Book.
for x in [1 2 3] { $x * $x | print }
# => 1
# => 4
# => 9What for iterates over
Value after in | Iterations |
|---|---|
| A list | One for each item |
| A table | One for each row, as a record |
A range such as 1..5 or 1.. | One for each number the range produces |
| A list stream | One for each item, as the item arrives |
null | None |
| Any other value | One, with the whole value (a record, a string, binary data) |
Language Notes
A record is a single value, so the loop runs once with the whole record. To loop over its fields, turn it into a table with
transpose, or useitemsinstead offor:for x in {name: nu, version: 117} { print ($x | describe) } # => record<name: string, version: int>let config = {name: nu, version: 117} for entry in ($config | transpose key value) { print $"($entry.key) = ($entry.value)" } # => name = nu # => version = 117A string, a number or binary data also runs the block once.
nullruns it zero times, so a value that may be missing needs no special case:for x in 42 { print $x }; for x in null { print "never runs" } # => 42fortakes the items of a stream one at a time, as they are produced. The block finishes with each item before the next one is produced:for x in (1..3 | each {|i| print $"producing ($i)"; $i }) { print $"got ($x)" } # => producing 1 # => got 1 # => producing 2 # => got 2 # => producing 3 # => got 3A range is not turned into a list first either, so a range without an end, such as
1.., works when the block leaves withbreak:for x in 1.. { if $x > 3 { break } print $x } # => 1 # => 2 # => 3The output of an external command is a byte stream, not a list. Split it with
linesto loop over its lines. Withoutlines, the output goes straight to the terminal and the block doesn't run:for line in (^printf "a\nb\n" | lines) { print $"line: ($line)" } # => line: a # => line: bTo get the index of each item as well, loop over the output of
enumerate:for item in ([a b] | enumerate) { print $"($item.index): ($item.item)" } # => 0: a # => 1: bLike
whileandloop,foris a statement. It evaluates tonothing, the values of its block are discarded, and it can't be used in a pipeline. Its block can updatemutvariables from the enclosing scope, but the loop variable itself can't be assigned:mut total = 0 for x in [1 2 3] { $total += $x } $total # => 6To collect a result for each item, use
each, which is an expression. See Loops in the Book for when to choose each one.