From 6442dc96d6d1f012604384a8aaaba95c5307f34d Mon Sep 17 00:00:00 2001 From: Fabian Homborg Date: Sun, 31 Jan 2021 13:13:12 +0100 Subject: [PATCH] docs: Add a loops section to index This was only in the tutorial - we really should improve the split here. --- doc_src/index.rst | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/doc_src/index.rst b/doc_src/index.rst index 68ae4678e..02fe1f37a 100644 --- a/doc_src/index.rst +++ b/doc_src/index.rst @@ -454,6 +454,53 @@ Some examples:: For more, see the documentation for the builtins or the :ref:`Conditionals ` section of the tutorial. +Loops and blocks +---------------- + +Like most programming language, fish also has the familiar :ref:`while ` and :ref:`for ` loops. + +``while`` works like a repeated :ref:`if `:: + + while true + echo Still running + sleep 1 + end + +will print "Still running" once a second. You can abort it with ctrl-c. + +``for`` loops work like in other shells, which is more like python's for-loops than e.g. C's:: + + for file in * + echo file: $file + end + +will print each file in the current directory. The part after the ``in`` is just a list of arguments, so you can use any :ref:`expansions ` there:: + + set moreanimals bird fox + for animal in {cat,}fish dog $moreanimals + echo I like the $animal + end + +If you need a list of numbers, you can use the ``seq`` command to create one:: + + for i in (seq 1 5) + echo $i + end + +:ref:`break ` is available to break out of a loop, and :ref:`continue ` to jump to the next iteration. + +:ref:`Input and output redirections ` (including :ref:`pipes `) can also be applied to loops:: + + while read -l line + echo line: $line + end < file + +In addition there's a :ref:`begin ` block that just groups commands together so you can redirect to a block or use a new :ref:`variable scope ` without any repetition:: + + begin + set -l foo bar # this variable will only be available in this block! + end + .. _expand: Parameter expansion