如何翻译鱼壳的`for`循环?

ico*_*ast 22 fish

我正在将一个脚本从Z shell翻译成Fish,我有一部分我无法弄清楚如何翻译:

  for (( i=0; i < $COLUMNS; i++ )); do
    printf $1
  done
Run Code Online (Sandbox Code Playgroud)

for我在Fish中可以找到的循环的唯一文档就是这种.我怎么会在Fish中这样做?

ico*_*ast 30

似乎Fish shell没有那种for循环,而是要求你采取不同的方法.(哲学显然是依赖于尽可能少的句法结构和运算符,并尽可能多地使用命令.)

这是我如何做到的,虽然我认为有更好的方法:

for CHAR in (seq $COLUMNS)
  printf $argv[1]
end
Run Code Online (Sandbox Code Playgroud)

这出现在函数内部,因此$argv[1].

  • 这是正确的,除了变量应该匹配:`for i in(seq $ COLUMNS); printf $ i; end` (6认同)
  • @ridiculous_fish:实际上`$ 1`是传递给这个循环所在的函数的其他内容......我没有意识到当时我发布它应该是`$ argv [1]`.我实际上并不关心$ CHAR或$ i,我只是使用`seq`在屏幕上打印`$ argv [1]`中的字符,每列一次.我会更新答案...... (2认同)

Adr*_*hum 12

I believe the answer from @iconoclast is the correct answer here.

I am here just to give an (not better) alternative.

a brief search in fish shell seems suggest it provides a while-loop in a form of :

while true
        echo "Loop forever"
end
Run Code Online (Sandbox Code Playgroud)

As in C/C++ 101, we learned that for loop can be (mostly) translated to a while loop by:

for (A; B; C) {
  D;
}
Run Code Online (Sandbox Code Playgroud)

translates to

A;
while (B) {
  D;
  C;
}
Run Code Online (Sandbox Code Playgroud)

That's what you can consider if the condition and "incrementation" is not a straight-forward one.