Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I translate this `for` loop for the fish shell?

Tags:

fish

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?

like image 366
iconoclast Avatar asked Jan 02 '14 01:01

iconoclast


People also ask

How do you write a fish script?

To be able to run fish scripts from your terminal, you have to do two things. Add the following shebang line to the top of your script file: #!/usr/bin/env fish . Mark the file as executable using the following command: chmod +x <YOUR_FISH_SCRIPT_FILENAME> .

How do you set up a fish shell?

Simply run fish_config to open the web client. From there, you can choose the themes, colors, prompts, inspect the FSH functions and variables, and see the history of commands used. Changes are, in turn, stored in the ~/. config/fish folder and can be accessed and edited there to dodge the optional web configuration.

Is fish a language?

<> (pronounced as if it were spelled as “fish”) is a stack-based, reflective, two-dimensional esoteric programming language. It draws inspiration from among others Befunge. It was invented by User:Harpyon in 2009.

Do bash commands work in fish?

Unlike the aforementioned shells, fish is not POSIX compliant, but it also doesn't intend to be. You can run Bash scripts in both Zsh and fish by adding the following shebang line to the first line of your Bash file.


2 Answers

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].

like image 123
iconoclast Avatar answered Oct 12 '22 15:10

iconoclast


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.

like image 27
Adrian Shum Avatar answered Oct 12 '22 13:10

Adrian Shum