6

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?

1
  • I wonder why people downvoted my question. I'd be happy to edit it if there is something to be improved.
    – gmagno
    May 22, 2020 at 12:44

3 Answers 3

6

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

echo 'some text' | read varname
4
  • 1
    if the pipe has newline separated content, only the first line is kept. What am I missing?
    – gmagno
    May 22, 2020 at 3:33
  • @ridiculous_fish, I don't understand why set a (cat -) does not consume the function's stdin. Can you elaborate? May 22, 2020 at 11:55
  • 1
    It's because fish doesn't propagate block redirections into command substitutions. Perhaps it should. May 31, 2020 at 19:29
  • Use read -z for null terminated, multi-line input (basically whatever you pipe through)
    – Valer
    May 10, 2021 at 12:35
6

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
1
  • 1
    The annoying thing, which is not a fault of your answer but rather of Fish, is that if nothing is piped through stdin, the while read command will wait for the user to input.
    – CJK
    Nov 30, 2020 at 9:00
0

If you want to store stdin into a scalar variable:

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

If you want to split lines in to a array:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.