Search code examples
bashfile-descriptor

How to write to a named file descriptor in Bash?


I have created a named file descriptor {out}:

$ exec {out}>out

But when I try to write to the named file descriptor, a new file gets created with the name of the file descriptor:

$ echo >&{out}
$ find . -name {out}
./{out}

The Bash manual says:

Each redirection that may be preceded by a file descriptor number may instead be preceded by a word of the form {varname}.

If I do it with a digit instead it works fine:

$ exec 3>out
$ echo test >&3
$ cat out
test

How to do the same with a named file descriptor?


Solution

  • The string inside the braces is just the name of a variable the shell will set for you, whose value is the file descriptor the shell allocates. The braces are not part of the name. In order to use it, just expand the variable in the proper context.

    $ exec {out}>out
    $ echo foobar >&$out
    $ cat out
    foobar
    

    In your example, the file {out} was created by

    echo >&{out}
    

    not the initial exec whose redirection created the file out stored the allocated file descriptor in the variable out.