bug-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Redirecting to /dev/stderr on Linux truncates files


From: Greg Wooledge
Subject: Redirecting to /dev/stderr on Linux truncates files
Date: Wed, 2 Jul 2014 12:35:33 -0400
User-agent: Mutt/1.4.2.3i

An IRC user initially reported this behavior, which is present in
at least bash 4.0, 4.2 and 4.3 on Linux (but *not* on HP-UX):

Redirection to /dev/stderr on platforms that have /dev/stderr as a
part of the native file system is *not* equivalent to >&2 as the
manual would seem to imply.

This is the code to reproduce the problem:

f() { echo STDOUT; echo STDERR >/dev/stderr; }
f >somefile 2>&1
cat somefile

On Linux this produces only one line: STDERR
On HP-UX this produces two lines, as expected.

Analysis indicates that on Linux, bash actually opens the operating
system's /dev/stderr file using this call (strace output):

open("/dev/stderr", O_WRONLY|O_CREAT|O_TRUNC, 0666) = 3

Since /dev/stderr has been redirected to a real file (through the
invocation's >somefile 2>&1 redirections), the open performed by the
second echo command is truncating the output already inside the file.

Rewriting the code like this works around the problem:

f() { echo STDOUT; echo STDERR >&2; }
f >somefile 2>&1
cat somefile

For reference, the manual says:

      Bash handles several filenames specially when they are used in
      redirections, as described in the following table:
      ...
           /dev/stderr
                File descriptor 2 is duplicated.

But on Linux, this does not work as advertised.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]