TheUnseen
TheUnseen

Reputation: 354

Is there any way for a fish function to read an optional input from pipe?

Is there any way to read data that has been piped to the function, from inside the function, but only if there is any? I tried it with cat like this:

function myPipe
    set -l pipe_input (cat -)
    echo $pipe_input # is never reached
end
echo test | myPipe

However, this results in the function stopping and waiting for pipe input, even if there actually was data piped to the function.

I would like fish to execute the rest of the function, even if there is no pipe input, so that I can handle the piped data.

Upvotes: 2

Views: 1338

Answers (2)

TheUnseen
TheUnseen

Reputation: 354

I finally figured out how to read optional input in a fish script:

The problem with set -l pipe_input (cat /dev/stdin) is that it will wait for input if the pipe '/dev/stdin' is empty, and therefore will stop execution at this point (with no pipe input).

  • Therefore you simply have to iterate over the stream:

cat /dev/stdin | while read line; set --append pipe_input "$line"; end

  • You can then easily go on and check if the variable (an array/list) has content:

    if test (count $pipe_input) -gt 0; echo "got pipe input: $pipe_input"; else echo "empty pipe"; end

Upvotes: 1

glenn jackman
glenn jackman

Reputation: 246799

You can test if stdin is connected to a pipe:

if isatty stdin
    set -l pipe_input ""     # not a pipe or redirection
else
    set -l pipe_input (cat -)
end

Ref: https://fishshell.com/docs/current/commands.html#isatty

Upvotes: 3

Related Questions