bug-bash
[Top][All Lists]
Advanced

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

Re: using exec to close a fd in a var crashes bash


From: Greg Wooledge
Subject: Re: using exec to close a fd in a var crashes bash
Date: Tue, 22 Aug 2023 22:20:01 -0400

On Wed, Aug 23, 2023 at 12:05:42PM +1000, Martin D Kealey wrote:
> On Wed, 23 Aug 2023, 05:29 Greg Wooledge, <greg@wooledge.org> wrote:
> 
> > Excuse me now, while I go and close several open FDs in the shell where
> > I tested something the other day, which I had no idea were left open.
> >
> 
> It's even worse than that; try:
> 
> echo Hi {X}>/dev/null
> ls -l "/proc/$$/fd/$X"

That's a really strange example.  I wonder what would lead someone to
write that particular redirection.  What's the intended outcome, in
terms of the variable X and the state of file descriptors?  If you
simply want to discard output, there's no reason I can think of to
use {X}>/dev/null instead of simply >/dev/null.

The thing I was testing was in response to this question, which was
posed as an exercise:

    Swap stderr and stdout of a shell command.

I gave two answers:

    cmd 3>&1 1>&2 2>&3 3>&-

and

    cmd {fd}>&1 1>&2 2>&$fd {fd}>&-

As it turns out, the second one does *not* close the temporary file
descriptor, so each time I ran the function while testing, an extra
file descriptor was left open.

But this variant *does* close it:

    cmd {fd}>&1 1>&2 2>&$fd
    exec {fd}>&-

I find this incredibly confusing.



reply via email to

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