help-bash
[Top][All Lists]
Advanced

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

Re: Why does MacOS always append to a redirected file descriptor even wh


From: Greg Wooledge
Subject: Re: Why does MacOS always append to a redirected file descriptor even when told to overwrite? Ubuntu only appends when strictly told to append
Date: Tue, 11 Feb 2025 17:28:26 -0500
User-agent: Mutt/1.10.1 (2018-07-13)

On Wed, Feb 12, 2025 at 04:33:32 +0800, Benjamin Lupton wrote:
>       printf '%s\n' '1' >/dev/stdout
>       printf '%s\n' '2' >/dev/stdout

> On Ubuntu this outputs:
> 2$
> 
> On MacOS this outputs:
> 1$
> 2$

The /dev/stdout device (and/or the underlying /dev/fd/ file system)
has different behavior on different operating systems.  MacOS is
based on BSD, not on Linux.

       Bash handles several filenames specially when they are used in redirec‐
       tions, as described in the following table.  If the operating system on
       which bash is running provides these special files, bash will use them;
       otherwise it will emulate them internally with the  behavior  described
       below.

              /dev/fd/fd
                     If  fd  is  a valid integer, file descriptor fd is dupli‐
                     cated.
              /dev/stdin
                     File descriptor 0 is duplicated.
              /dev/stdout
                     File descriptor 1 is duplicated.
              /dev/stderr
                     File descriptor 2 is duplicated.

Since both Linux and BSD/MacOS provide /dev/stdout, you get the semantics
of that device on the target OS, rather than a consistent internal
implementation.

In the case of the above example (the only one I've kept in this reply),
you're opening /dev/stdout two separate times.  It would appear that on
Linux, each time you open it in this way, you clobber the existing file,
if there is one.  Whereas on MacOS, presumably this is not the case.

When you open the file in append mode, you don't clobber existing data,
and every write will first atomically move the file offset to the end
of the file.

This issue (different behavior of /dev/stdout on different systems) has
definitely appeared on the *-bash mailing lists a few times before, but
searching for it is difficult for me.  I did find one thread.  See
<https://lists.gnu.org/archive/html/bug-bash/2014-09/msg00049.html>
for a similar reply to this one.



reply via email to

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