help-bash
[Top][All Lists]
Advanced

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

Re: Redirection and subshells and file position pointer


From: Greg Wooledge
Subject: Re: Redirection and subshells and file position pointer
Date: Thu, 10 Jul 2025 07:09:27 -0400
User-agent: Mutt/1.10.1 (2018-07-13)

On Thu, Jul 10, 2025 at 07:23:29 +0200, Andreas Kähäri wrote:
> On Thu, Jul 10, 2025 at 07:17:22AM +0200, Kusalananda Kähäri wrote:
> > Just thinking aloud about the non-portability of "tee /dev/stderr"...
> > 
> > Bash handles /dev/stderr specially when it's used in a redirection, so
> > changing "tee /dev/stderr" into "tee >/dev/stderr" might get rid of the
> > portability issue?

This is only true on systems that don't have their own /dev/stderr device
nodes (e.g. commercial Unix).  On systems that *do* have those device
nodes, bash actually opens them.

This is documented in the bash 5.2 man page; not sure how far back the
documentation goes.

       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.

And a demonstration:

hobbit:~$ strace bash -c ': >/dev/stdout'
execve("/usr/bin/bash", ["bash", "-c", ": >/dev/stdout"], 0x7ffd8182b1e0 /* 57 
vars */) = 0
[...]
openat(AT_FDCWD, "/dev/stdout", O_WRONLY|O_CREAT|O_TRUNC, 0666) = 3
fcntl(1, F_GETFD)                       = 0
fcntl(1, F_DUPFD, 10)                   = 10
fcntl(1, F_GETFD)                       = 0
fcntl(10, F_SETFD, FD_CLOEXEC)          = 0
dup2(3, 1)                              = 1
close(3)                                = 0
dup2(10, 1)                             = 1
fcntl(10, F_GETFD)                      = 0x1 (flags FD_CLOEXEC)
close(10)                               = 0
[...]

I believe this is done to maintain consistent behavior among shells on
the same system.  If some other shell implements "echo >/dev/stderr"
by opening the device node, but bash implements it with internal
redirections, then you would get different results depending on which
shell ran the command.  (The OP of this thread discovered this the
hard way!)

> > The stream would be duplicated onto standard output and also redirected
> > to whatever Bash thinks /dev/stderr is (rather than duplicated to the
> > possibly non-existent /dev/stderr path and standard output).
> 
> Duh. Someday soon, I will learn to test code before deciding what it
> does.  The "tee >/dev/stderr" command will not write anything to
> standard output, so the command substitution in Greg's code wouldn't
> capture anything.



reply via email to

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