Bash – Write to stderr

bashstderr

I'm using stderred to color all output streamed to stderr red. It's working fine. But when I write my own bash script and throw an error with echo 'error' 1>&2, it doesn't color the output in red. I reckon this is, because the command simply redirects the output to wherever the stderr file descriptor points to, but doesn't properly mark the message as belonging to stderr. Is that so? How can I properly write to stderr in bash?

Best Answer

It appears that the program is re-writting the various write() functions to detect whether you are printing to file descriptor 2 and then adding the relevant escape codes to make the output red at the terminal.

Unfortunately, in shell, when you do something like

echo "foo" 1>&2 

The function will still be calling write (or some other similar system call) on file descriptor 1. The output appears on fd 2 since file descriptor 1 has been dupped to file descriptor 2 by your shell.

Unfortunately, I don't know of way to write /directly/ to fd 2 in shell, but you can use awk. A function like this will write the arguments directly to file descriptor 2.

error() {
  awk " BEGIN { print \"$@\" > \"/dev/fd/2\" }"
}

I believe this is a feature of GNU awk that isn't part of POSIX but it also works on the awk provided on OS X.

Related Question