Nushell 0.32 added support for typical for loops:
With the new
Nushell 0.32 release notesfor..in
command, you can write more natural iterating loops:
> for $x in 1..3 { echo ($x + 10) }
───┬────
0 │ 11
1 │ 12
2 │ 13
───┴────
Compared to what we have in Bash and others (and given my limited understanding) the most notable difference is that there is no “do”, but instead a curly bracket defining what should be done.
Also, remember that Nushell has an understanding of various data types, so the iterator in the example above is indeed of type “int”. Just stitching it together with another string doesn’t work:
❯ for $i in 1..3 {echo ("/home/" + $i) }
error: Coercion error
┌─ shell:31:23
│
31 │ for $i in 1..3 {echo ("/home/" + $i) }
│ ^^^^^^^^ -- integer
│ │
│ string
Instead, make sure to echo the iterator:
❯ for $i in 1..3 {echo $"/home/(echo $i)" }
───┬─────────
0 │ /home/1
1 │ /home/2
2 │ /home/3
───┴─────────
For comparison, if you have a set of strings you can provide them in a table and stitch them together easily:
❯ for $i in [a b c d] {echo ("/home/" + $i) }
───┬─────────
0 │ /home/a
1 │ /home/b
2 │ /home/c
3 │ /home/d
───┴─────────