4

The fish documentation gives the following way to run a for loop.

for i in 1 2 3 4 5;
    echo $i
end

Let us say I want to run a command 1000 times, How can I do it?

2 Answers 2

10

Same documentation, https://fishshell.com/docs/current/language.html#loops-and-blocks :

for i in (seq 1 5)
    echo $i
end

replace seq 1 5 with the numbers you want to get, e.g., seq 14 1000 to get the numbers from 14 to 1000; if you want to start at 1, it's OK to omit the starting point, i.e., write seq 1000.

This, by the way, is like very classical UNIX shells; doesn't feel very modern. (In bash and zsh you can do for i in {1..1000}, which I consider easier and clearer to read, not to mention that it saves actually running an external program seq and buffering its output.)

Another way, which doesn't rely on coreutils (which is kind of a sad thing to rely on if you're not a GNU program nor a POSIX shell), would be using the while loop and purely fish builtin functions:

set counter 0
# -lt: less than
while test $counter -lt 1000;
    set counter (math $counter + 1)
    echo $counter
end
2
  • See also repeat 1000 cmd in tcsh or zsh. I guess, for simple commands, one could easily implement a function that does the same in fish. Commented Jan 16, 2023 at 13:56
  • In fish that could be function repeat -a n; while test $n -gt 0; $argv[2..]; set n (math $n - 1); end; end TODO add a guard to validate $n Commented Jan 16, 2023 at 15:36
5

Turns out there is a program in the gnu-coreutils called seq which prints out a sequence of numbers.

So to run a command n times, the following loop can be used.

for i in (seq n);
    echo $i
end
2
  • this works for small n, as the shell needs to generate the sequence from 1...n before going through the for loop. Try the iterative method for less ram usage Commented Nov 6, 2023 at 20:58
  • @mdave16 fish is almost exclusively used for interactive shells, not as automation shell in very resource-constrained machines. You can run this up to 524288 (tested on fish 3.7.0 on x86_64); that uses less than 150 MB of RAM. If you're processing more than half a million anything in a shell function, I hope you're not doing it with less than half a Gigabyte of RAM. In fact, rule of thumb: whatever you do more than 2000 times, don't do it in your shell, no matter what your shell is; you probably have a problem that benefits from a more fully-fledged language. Commented Feb 24 at 12:56

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.