Shell – Why is it that these two ‘cat’ commands result differently

io-redirectionshell

Let's assume that infile contains a specific text, and I were to execute the following set of commands:

exec 3<infile

cat -n <&3

cat -n <&3

The first instance of cat will display the file's contents, but the second time does not seem to be doing anything. Why do they differ?

Best Answer

They look like the same command but the reason they differ is the system state has changed as a result of the first command. Specifically, the first cat consumed the entire file, so the second cat has nothing left to read, hits EOF (end of file) immediately, and exits.

The reason behind this is you are using the exact same file description (the one you created with exec < infile and assigned to the file descriptor 3) for both invocations of cat. One of the things associated with an open file description is a file offset. So, the first cat reads the entire file, leaves the offset at the end, and the second one tries to pick up from the end of the file and finds nothing to read.

Related Question