0

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

6

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. 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 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
1
  • 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
    – mdave16
    Nov 6, 2023 at 20:58

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .