52

I know this has been an issue for a while and I found a lot of discussion about it, however I didn't get which would be finally a way to get it done: pipe both, stdout and stderr. In bash, this would be simply:

cmd 2>&1 | cmd2
Anton Harald
  • 5,772
  • 4
  • 27
  • 61

2 Answers2

56

That syntax works in fish too. A demo:

$ function cmd1
      echo "this is stdout"
      echo "this is stderr" >&2
  end

$ function cmd2
      rev
  end

$ cmd1 | cmd2
this is stderr
tuodts si siht

$ cmd1 &| cmd2
rredts si siht
tuodts si siht

Docs: https://fishshell.com/docs/current/language.html#redirects

Rptx
  • 1,159
  • 1
  • 12
  • 17
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
  • perfect. it turned out that I used an older version. – Anton Harald May 30 '16 at 20:35
  • 23
    to redirect to a file, `echo meow > /tmp/meow 2>&1` works for me. you need the stderr redirection after the stdout redirection. – nhooyr Jan 31 '18 at 15:36
  • Why do you use `sh -c` in function `cmd1`, while `echo "this is stdout"; echo "this is stderr" >&2` simply works – enzotib Apr 26 '19 at 07:53
  • As for why you need `2>&1` after `> /tmp/meow`, it's because redirection is “dumb”. If you do `2>&1` first, `stderr` gets sent to `stdout`, which is the terminal, and then if you redirect `stdout`, `stderr` doesn't get the message and remains pointed at the terminal. – BallpointBen Jul 14 '23 at 04:27
13

There's also a handy shortcut, per these docs

&>

Here's the relevant quote (emphasis and white space, mine):

As a convenience, the redirection &> can be used to direct both stdout and stderr to the same destination. For example:

echo hello &> all_output.txt

redirects both stdout and stderr to the file all_output.txt. This is equivalent to echo hello > all_output.txt 2>&1.

Navelgazer
  • 185
  • 1
  • 8
  • 3
    Thanks for this! Worth noting that more than just stdout and stderr but all output FDs seem to be forwarded with this. I was struggling with a parallel app that was outputting multiple processes via &3 &4 etc. &> gets them all which is super helpful. – BoeroBoy Feb 01 '22 at 16:46
  • 1
    After following S.O.'s little badge treats back to this post, reread @BoeroBoy's comment, and realized that the `>` in `&>` is easy to remember once you know that it "gets them all," since it looks like a funnel (or, as we learned in gradeschool, an an alligator) swallowing _all_ the outputs. – Navelgazer Mar 28 '22 at 06:47