Write to stderr

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.


That software hooks the write() system calls that apprear to write at file descriptor 2, that is known as stderr.

It is a shared library (so recompilation of the kernel is not necessary). As descripted in the installation manual it takes use of the environment varaible LD_PRELOAD. The dynamic linker can be influenced into modifying its behavior during the program's execution. These variables adjust the runtime linking process by searching for shared libraries at alternate locations.

The executable /bin/bash itself does not honour such variables, so bash itself uses the original pallette of system calls, not the modified ones. The redirection you mentioned in your question happend in bash. Not in the executable of echo. If echo could wirte to the error descriptor by itself (not via bash) the output would be red.

Python can write to stderr. See the proof (that should appear in red):

python -c 'import os; os.write(2, "error")'

Tags:

Bash

Stderr