在 fish shell 函数中如何将 stdin 传递给变量?

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

这是我得到的:

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

第一个例子:

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

第二个例子:

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

有什么建议吗?

在鱼shell(和其他)中,你想要read:

echo 'some text' | read varname

跟进@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

所以你得到

$ echo foo bar | stdin2var
1
foo bar

$ seq 10 | stdin2var
10
1
2
3
4
5
6
7
8
9
10

如果要将标准输入存储到标量变量中:

function stdin2var
    read -l -z a

    set --show a
    echo $a
end

echo some text\nsome more text | stdin2var
# $a: set in local scope, unexported, with 1 elements
# $a[1]: length=25 value=|some text\nsome more text\n|
# some text
# some more text

如果要将行拆分为数组:

function stdin2var
    set -l a
    IFS=\n read -az a

    set --show a
    for line in $a
        echo $line
    end
end

echo some text\nsome more text | stdin2var
# $a: set in local scope, unexported, with 2 elements
# $a[1]: length=9 value=|some text|
# $a[2]: length=14 value=|some more text|
# some text
# some more text