Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fish: Iterate over a string

Tags:

shell

fish

How would you iterate over a string in the fish shell?

Unfortunately iterating over a string isn't as straight forward as iterating over a list:

↪ for c in a b c
      echo $c
  end
a
b
c

↪ for c in abc
      echo $c
  end
abc
like image 792
Dennis Avatar asked Mar 11 '18 18:03

Dennis


People also ask

How do you put a path on a fish?

fish_add_path is a simple way to add more components to fish's PATH . It does this by adding the components either to $fish_user_paths or directly to $PATH (if the --path switch is given). It is (by default) safe to use fish_add_path in config.

How do you switch to a fish shell?

Switching to fish? If you wish to use fish (or any other shell) as your default shell, you need to enter your new shell's executable /usr/local/bin/fish in two places: add /usr/local/bin/fish to /etc/shells. change your default shell with chsh -s to /usr/local/bin/fish.

How do I run a fish shell 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> .


1 Answers

The for loop in fish operates on a list.

for VARNAME in [VALUES...]; COMMANDS...; end

The builtin string command (since v2.3.0) can be used to split a string into a list of characters.

↪ string split '' abc
a
b
c

The output is a list, so array operations will work.

↪ for c in (string split '' abc)
      echo $c
  end
a
b
c

A more complex example iterating over the string with an index.

↪ set --local chars (string split '' abc)
  for i in (seq (count $chars))
      echo $i: $chars[$i]
  end
1: a
2: b
3: c
like image 199
Dennis Avatar answered Oct 13 '22 12:10

Dennis