Bash – How Does `cat <> file` Work

bashio-redirectionshell

cat < file prints the contents of file to stdout.

cat > file reads stdin until Ctrl+D is detected and the input text is written to file.

cat <> file, at least in my version of Bash, prints the contents of file happily (without error), but doesn't modify the file nor does it update the modification timestamp.

How does the Bash standard justify the seemingly ignored > in the third statement – and, more importantly, is it doing anything?

Best Answer

Bash uses <> to create a read-write file descriptor:

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.

cat <> file opens file read-write and binds it to descriptor 0 (standard input). It's essentially equivalent to < file for any sensibly-written program, since nobody's likely to try writing to standard input ordinarily, but if one did it'd be able to.

You can write a simple C program to test that out directly - write(0, "hello", 6) will write hello into file via standard input.

<> should also work in any other POSIX-compliant shell with the same effect.