14

In bash script,

echo "error" 1>&2 | tee -a log

will print stderr in screen but no log to file, how to do these at same time?

timy
  • 501
  • 1
  • 6
  • 17

4 Answers4

13

To echo the text to both the log file and stderr, but not stdout, try this:

echo "error" | tee -a log 1>&2
ams
  • 24,923
  • 4
  • 54
  • 75
  • I'm not 100% sure what the OP wanted to do, but this is by far the best solution for my own case. I think the problem is that it's easy to think the redirection should be applied to the `echo`, but doing it to the `tee` command works perfectly, thanks! – Haravikk Jul 10 '13 at 13:14
8
echo "error" 1>&2 | tee -a log

With the first part 1>&2, what you are saying is: "Redirect stdout to stderr". So the echoed output "error" goes to stderr.

Pipe (|) only reads from stdout, not stderr. So tee doesn't get any stdin at all from the pipe. Hence, it appends nothing to the log file.

P.P
  • 117,907
  • 20
  • 175
  • 238
  • 3
    +1. Very fine answer, except for a solution: it might be worthwile to mention `2>&1` as correct for this purpose. – glglgl Nov 13 '12 at 10:58
  • yes, ic. But how to echo to stderr and write err log to file? – timy Nov 13 '12 at 11:41
  • @timy If you *redirect* stderr to stdout then you can do that: `echo "error" 2>&1 | tee -a log`. Now both stderr will also go to stdout and you can see both on the screen and will also append to the log. – P.P Nov 13 '12 at 11:49
  • @KingsIndian 2>&1 will output nothing to stderr, which is I want to do here. – timy Nov 13 '12 at 12:01
  • @timy Unless some acutal error occurs "echo"ed output will only go `stdout`. You are right that `2>&1` will write nothing to stderr. But since stdout & stderr both go to console, you don't really need to worry about that. – P.P Nov 13 '12 at 12:14
7

To view both stdout and stderr on the console and send both streams to a log, redirect stderr to stdout as shown below:

progam.sh 2>&1 | tee -a log
dogbane
  • 266,786
  • 75
  • 396
  • 414
0

But default only stdout is passed along in pipes, so that in

$ echo "error" | tee 

tee only sees the stout from the echo, not the stderr. stderr will still be displayed in the terminal.

Benjamin Bannier
  • 55,163
  • 11
  • 60
  • 80