Sending output to /dev/stderr vs. >&2

portabilitystderr

In scripts, errors are usually sent to file descriptor 2 with &2, ie:

echo "error" >&2

Sometimes /dev/stderr is used instead:

echo "error" > /dev/stderr 

Looking at /dev/stderr, I see that it is only a symlink to /proc/self/fd/2 , which in turn is a symlink to /dev/pts/5 (on my current terminal).

Seems little bit over complicated. Is there some logic behind that ?

Is using /dev/stderr and &2 equivalent ?

Is any of those preferred over the other ?

Best Answer

The special device /dev/stderr is system-specific, while the file descriptor 2 (not the special device /proc/self/fd/2) is portable. If you want to write non-portable code, those special devices are a good place to start.

There are a few systems with /dev/stderr: Linux, of course, and OSX. But OSX has no /proc filesystem, and its /dev/stderr is a link to /dev/fd/2.

Further reading:

Related Question