specifying file descriptor number? specifying file descriptor number? unix unix

specifying file descriptor number?


I believe you are right that sometimes file descriptors may already be in use. I got this from http://tldp.org/LDP/abs/html/io-redirection.html#FTN.AEN17716

"Using file descriptor 5 might cause problems. When Bash creates a child process, as with exec, the child inherits fd 5 (see Chet Ramey's archived e-mail, SUBJECT: RE: File descriptor 5 is held open). Best leave this particular fd alone."

The solutiont to this is specified in section 3.6 paragraph 2 of the bash manual.

Each redirection that may be preceded by a file descriptor number may instead be preceded by a word of the form {varname}. In this case, for each redirection operator except >&- and <&-, the shell will allocate a file descriptor greater than 10 and assign it to {varname}. If >&- or <&- is preceded by {varname}, the value of varname defines the file descriptor to close.

For example

#!/bin/bashexec {NEW_STDOUT}>&1echo "Hello" >&$NEW_STDOUTexec {NEW_STDOUT}>&-


Also, file descriptors are assigned sequentially, so if you know 0, 1, 2, ..., n are already opened and none of them have been closed, the next will be n+1.