gamontbr
gamontbr

Reputation: 23

What is the purpose of these file descriptors closes?

I'm following this example from Advaced Bash Guide,IO redirection, that shows ' Redirecting only stderr to a pipe'. I understood how it works except when it close fd 3. why it need close fd 3 in each command when the last command closes is globally ?

exec 3>&1
ls -l 2>&1 >&3 3>&- | grep bad 3>&-
exec 3>&-

Upvotes: 2

Views: 96

Answers (1)

LaC
LaC

Reputation: 12824

In the shell, initially you have 1:terminal, 2:terminal. Then 1 is duplicated so that 3:terminal. When ls is executed, the file descriptors are inherited, but the pipe replaces the first, so that you have 1:pipe, 2:terminal, 3:terminal; then the redirects make it 1:terminal, 2:pipe, (3:closed). Meanwhile, grep has 0 connected to the pipe, and inherits 1:terminal, 2:terminal, 3:terminal, but the redirect turns it into 1:terminal, 2:terminal, (3:closed). Finally, back in the shell, 3 is closed, returning to the initial state of 1:terminal, 2:terminal.

The thing to understand is that file descriptors are inherited when a process is forked, but become independent from then on, so each process's descriptor 3 must be closed separately. In this case, there would probably be no harm in leaving it open for ls and grep, but for tidyness it's closed anyway.

Upvotes: 3

Related Questions