在 Fish shell 函数中,如何将标准输入通过管道传输到变量?

gma*_*gno 6 function fish

这是我得到的:

function stdin2var
    set a (cat -)
    echo $a
end
Run Code Online (Sandbox Code Playgroud)

第一个例子:

$ echo 'some text' | stdin2var
# should output "some text"
Run Code Online (Sandbox Code Playgroud)

第二个例子:

$ echo some text\nsome more text | stdin2var
# should output: "some text
some more text"
Run Code Online (Sandbox Code Playgroud)

有小费吗?

rid*_*ish 8

在鱼壳(和其他)中,您想要read

echo 'some text' | read varname
Run Code Online (Sandbox Code Playgroud)

  • 这是因为 Fish 不会将块重定向传播到命令替换中。也许应该如此。 (3认同)

gle*_*man 6

继 @ridiculous_fish 的回答之后,使用 while 循环来消耗所有输入:

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
Run Code Online (Sandbox Code Playgroud)

所以你得到

$ echo foo bar | stdin2var
1
foo bar

$ seq 10 | stdin2var
10
1
2
3
4
5
6
7
8
9
10
Run Code Online (Sandbox Code Playgroud)