How do I translate this `for` loop for the fish sh

2020-06-07 04:32发布

问题:

I'm translating a script from Z shell to Fish, and I've got this one part I can't figure out how to translate:

  for (( i=0; i < $COLUMNS; i++ )); do
    printf $1
  done

The only documentation for for loops I can find in Fish is for this kind. How would I do this in Fish?

回答1:

It appears that the Fish shell does not have that kind of for loop, but instead requires you to take a different approach. (The philosophy is apparently to rely on as few syntactic structures and operators as possible, and do as much with commands as possible.)

Here's how I did it, although I assume there are better ways:

for CHAR in (seq $COLUMNS)
  printf $argv[1]
end

This appears inside a function, hence the $argv[1].



回答2:

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

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

for (A; B; C) {
  D;
}

translates to

A;
while (B) {
  D;
  C;
}

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



标签: fish