On Wed, Aug 23, 2023 at 12:05:42PM +1000, Martin D Kealey wrote:
> On Wed, 23 Aug 2023, 05:29 Greg Wooledge, <[email protected]> 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.