Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 593
ceving Avatar asked Oct 28 '14 11:10

ceving


People also ask

What is file descriptor in Bash?

In the Bash shell, file descriptors (FDs) are important in managing the input and output of commands. Many people have issues understanding file descriptors correctly. Each process has three default file descriptors, namely: Code.

How do I use file descriptor in Linux?

On Linux, the set of file descriptors open in a process can be accessed under the path /proc/PID/fd/ , where PID is the process identifier. File descriptor /proc/PID/fd/0 is stdin , /proc/PID/fd/1 is stdout , and /proc/PID/fd/2 is stderr .

How do I redirect a file in Bash?

For utilizing the redirection of bash, execute any script, then define the > or >> operator followed by the file path to which the output should be redirected. “>>” operator is used for utilizing the command's output to a file, including the output to the file's current contents.

What is and2 in Bash?

and >&2 means send the output to STDERR, So it will print the message as an error on the console. You can understand more about shell redirecting from those references: https://www.gnu.org/savannah-checkouts/gnu/bash/manual/bash.html#Redirections.


1 Answers

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.

like image 165
chepner Avatar answered Sep 28 '22 02:09

chepner