0

I know variations of this question have been asked and answered several times before, but I'm either misunderstanding the solutions, or am trying to do something eccentric. My instinct is that it shouldn't require tee but maybe I'm completely wrong...

Given a command like this:

sh
echo "hello"

I want to send it to STDERR so that it can be logged/seen on the console, and so that it can be sent to another command. For example, if I run:

sh
echo "hello" SOLUTION>&2 > myfile.txt

(SOLUTION> being whatever the answer to my problem is)

I want:

  • hello to be shown in the console like any other STDERR message
  • The file myfile.txt to contain hello
Community
  • 1
  • 1
dancow
  • 3,228
  • 2
  • 26
  • 28
  • AFAIK, bash stream redirection cannot duplicate a stream. That's the whole point of `tee`'s existence. And as far as I can see, your question is an exact duplicate of https://stackoverflow.com/q/3141738 – Siguza Aug 17 '16 at 23:35

2 Answers2

3

There's no need to redirect it to stderr. Just use tee to send it to the file while also sending to stdout, which will go to the terminal.

echo "hello" | tee myfile.txt

If you want to pipe the output to another command without writing it to a file, then you could use

echo "hello" | tee /dev/stderr | other_command

You could also write a shell function that does the equivalent of tee /dev/stderr:

$ tee_to_stderr() {
    while read -r line; do
        printf "%s\n" "$line";
        printf "%s\n" "$line" >&2
    done
}

$ echo "hello" | tee_to_stderr | wc
hello
       1       1       6

This doesn't work well with binary output, but since you intend to use this to display text on the terminal that shouldn't be a concern.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Thanks! I've seen some variation of this answer, but with the caveat that not all systems have `/dev/stderr` and I was wondering what it would look like using the stderr file descriptor. On the other hand, the lack of universal standard on `/dev/stderr` is not a huge concern of mine so this answer works just as well for me. – dancow Aug 18 '16 at 19:35
  • 1
    The shell doesn't have any built-in mechanism for replicating output to multiple fds. And tee doesn't have an option for writing directly to an fd. You could write a shell function that does it. – Barmar Aug 18 '16 at 21:14
1

tee copies stdin to the files on its command line, and also to stdout.

echo hello | tee myfile.txt >&2

This will save hello in myfile.txt and also print it to stderr.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578