Question 1. What will happen if we close a input file descriptor as if it is a output file descriptor? (or vice versa).

For Example,

    $ exec 5<&2
    $ exec 5>&-

In my linux box, any error does not happen on sh and bash. And POSIX seems not to say we SHOULD close input file descriptos with <-.

The redirection operator:


... If word evaluates to '-', file descriptor n, or standard input if n is not specified, shall be closed. Attempts to close a file descriptor that is not open shall not constitute an error. ...

So is it also a correct way that to close a input file descriptor as if it is for output?

Question 2. If the above code is wrong and we should close a input file descritor with <-, how can we close a file descriptor for reading and writing?

  $ exec 5<>&file
  $ #How to close the file descritor 5? 

Question 3. According to the above POSIX specification, we shall not see any error when we attempt to close a file descriptor that is not open. What is the merit of this way?

  • Your syntax is wrong. To close a descriptor you need &-. A - by itself creates a file called -. You probably have a few of those from your testing now. – jw013 May 16 '14 at 0:08
  • @jw013 You are right, I corrected it. But I am still wondering if it is correct that to close input file descriptor with >&-. – MS.Kim May 16 '14 at 0:49
  • In practice, closing a file descriptor in the shell probably means using the close() system interface, which works on all file descriptors regardless of what mode they were opened in. This is probably why closing shell file descriptors with the wrong operator still works. However, nowhere does POSIX guarantee this will work, so it would be unwise to rely on such behavior. – jw013 May 16 '14 at 1:03
  • 1
    Thanks for comment. I understand what you mean. But usually, POSIX uses the phrase "the result is unspecified" to avoid any ambiguities. But in this case, POSIX says nothing about it. That was my main reason to ask. And what about question 3? How correctly to close file descriptor for reading and writing?. – MS.Kim May 16 '14 at 1:51
  • You raise a good point about <>. It appears POSIX may be a bit under-specified here, and there does not seem to be a "good" answer to your question. If you need to use <> in a POSIX environment, it seems like a fairly safe assumption that on most implementations any one of >&- and <&- will work though. – jw013 May 16 '14 at 2:20