18

I have a probably pretty easy beginner question: How do I echo from a shell script into both stdout and stderr? I know that I can echo to stderr echo "foo" 1>&2 but I need the output in both. I tried some Googling but nothing worked.

Community
  • 1
  • 1
NumberFour
  • 3,371
  • 7
  • 46
  • 69
  • possible duplicate of [Redirecting bash stdout/stderr to two places?](http://stackoverflow.com/questions/670784/redirecting-bash-stdout-stderr-to-two-places). Not exactly the same, but the answer still works if you just make your process `cat >&2` – Nemo Jul 28 '11 at 01:08

2 Answers2

26

This should do it

 echo "foo" | tee /dev/stderr 
Soren
  • 14,094
  • 4
  • 38
  • 66
  • 2
    That assumes your systems supports `/dev/stderr`. I think most or all modern Unix-like systems do, but just in case you're concerned about ancient systems: `line="foo"; echo "$line" ; echo "$line" 1>&2`. It should be easy enough to wrap that in an alias or function. – Keith Thompson Jul 29 '11 at 16:26
  • 1
    Note: you don't need `1` in `1>&2`, `echo $line >&2` does the same. – TWiStErRob Feb 27 '14 at 13:49
  • FYI - busybox's' init doesn't seem to support `/dev/stderr`. – ACK_stoverflow Jul 15 '20 at 18:36
13
echo foo | tee >(cat >&2)

This will work even if stderr is not supported.

Note: Soren's answer will not work if you have su'ed to another account that does have write permissions to the tty; but mine will.

gle
  • 161
  • 1
  • 2
  • 1
    Doesn't it require bash? Simple Bourne shell outputs `sh: Syntax error: "(" unexpected (expecting word)` – zezollo Apr 03 '21 at 13:47