Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In a fish shell function how to pipe stdin to a variable?

Tags:

function

fish

Here's what I got:

function stdin2var
    set a (cat -)
    echo $a
end

First example:

$ echo 'some text' | stdin2var
# should output "some text"

Second example:

$ echo some text\nsome more text | stdin2var
# should output: "some text
some more text"

Any tips?

like image 660
gmagno Avatar asked May 22 '20 03:05

gmagno


People also ask

How do you set a variable in a fish shell?

Unlike other shells, fish has no dedicated VARIABLE=VALUE syntax for setting variables. Instead it has an ordinary command: set , which takes a variable name, and then its value.

How do you put a path on a fish shell?

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. fish, or it can be used once, interactively, and the paths will stay in future because of universal variables.

How do I customize my fish prompt?

To create a custom prompt create a file ~/. config/fish/functions/fish_prompt. fish and fill it with your prompt. Is there a way to save multiple prompts, or add to the list of available prompts that are displayed when you run fish_config?

How do you personalize fish?

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.


2 Answers

In fish shell (and others), you want read:

echo 'some text' | read varname
like image 169
ridiculous_fish Avatar answered Sep 24 '22 11:09

ridiculous_fish


Following up on @ridiculous_fish's answer, use a while loop to consume all input:

function stdin2var
    set -l a
    while read line
        set a $a $line
    end
    # $a is a *list*, so use printf to output it exactly.
    echo (count $a)
    printf "%s\n"  $a
end

So you get

$ echo foo bar | stdin2var
1
foo bar

$ seq 10 | stdin2var
10
1
2
3
4
5
6
7
8
9
10
like image 32
glenn jackman Avatar answered Sep 22 '22 11:09

glenn jackman