Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Echo to both stdout and stderr

Tags:

linux

shell

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.

like image 509
NumberFour Avatar asked Jul 28 '11 00:07

NumberFour


People also ask

How can we send both stdout and stderr to a file?

Either use this construct: cmd >>file. txt 2>&1 where >> file appends the output to the file and 2>&1 redirects the stderr to stdout .

Why do we have both stdout and stderr as ways of printing to the screen?

These three special file descriptors handle the input and output from your script or a process. while STDIN or Standard Input helps the Linux Process or a script to get its input from the user ( typing in the keyboard) the Standard output STDOUT and Error STDERR helps to display the result to the user on the monitor.

Does Echo write to stdout?

The echo command writes text to standard output (stdout). Some common usages of the echo command are piping shell variable to other commands, writing text to stdout in a shell script, and redirecting text to a file.

How do I redirect stderr and stdout?

The regular output is sent to Standard Out (STDOUT) and the error messages are sent to Standard Error (STDERR). When you redirect console output using the > symbol, you are only redirecting STDOUT. In order to redirect STDERR, you have to specify 2> for the redirection symbol.


2 Answers

This should do it

 echo "foo" | tee /dev/stderr 
like image 50
Soren Avatar answered Sep 20 '22 14:09

Soren


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.

like image 44
gle Avatar answered Sep 19 '22 14:09

gle