Bash – Closing a File Descriptor: >&- vs <&-

bashio-redirectionshell

In the bash tutorial I am reading, it says that if you open a file descriptor for reading, i.e.

exec 3< echolist

Then you must close it like this,

exec 3<&-

However, if you open a file descriptor for writing, it must be closed like this:

exec 3>&-

Yet when I look on the internet, I see people opening files and then closing them with this:

exec 3>&- 

NOTE: when, according to the tutorial, they should be using exec 3<&1.

So my question is, can all file descriptors be closed via exec n>&- where n is the file descriptor number? Regardless if it was opened for reading, writing, or both?

Best Answer

You can close file descriptor using both <&- and >&-, bash will parse two syntax as the same.

From file y.tab.c in bash source code:

5385   /* Hack <&- (close stdin) case.  Also <&N- (dup and close). */                
5386   if MBTEST(character == '-' && (last_read_token == LESS_AND || last_read_token == GREATER_AND))
5387     return (character);
Related Question