2

I recently saw this SO answer

Bash natively supports tcp connections as file descriptors. To use:

exec 6<>/dev/tcp/ip.addr.of.server/445
echo -e "GET / HTTP/1.0\n" >&6
cat <&6

I'm using 6 as the file descriptor because 0, 1, 2 are stdin, stdout, and stderr. 5 is sometimes used by Bash for child processes, so 3, 4, 6, 7, 8, and 9 should be safe.

What I don't understand and have never seen before is the exec 6<> in the first line. What does that mean (given that 6 can presumably be any generic file descriptor, as discussed in the quote)? Particularly I don't recall ever seeing <> in a bash script before.

Apologies if this is a FAQ, but my usual search engines either don't record or refuse to search for <>.

Community
  • 1
  • 1
TomRoche
  • 1,464
  • 1
  • 16
  • 25

2 Answers2

2

This is a bash extension that allows opening a single descriptor in read-write mode. This is typically used with sockets, to allow bidirectional communication (e.g. reading a request and sending a reply).

From the bash man page

Opening File Descriptors for Reading and Writing

The redirection operator
     [n]<>word
causes the file whose name is the expansion of word to be opened for both reading and writing on file descriptor n, or on file descriptor 0 if n is not specified. If the file does not exist, it is created.

Community
  • 1
  • 1
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Thanks! for extra credit: in which bash version was this introduced? Alternatively, for which bash versions should I expect a script using this syntax to fail? – TomRoche Oct 21 '14 at 21:10
1

Using "bash redirect" as my search term I found that syntax is explained as a way to create a file descriptor with the given name, 6 in this case. The file that will be open follows the <> syntax.

Thus it looks like bash is opening a file descriptor for I/O and sending an HTTP GET and dumping the output to stdout.

Dan S
  • 9,139
  • 3
  • 37
  • 48