Introduction

Wikipedia has a section on the page for the Unix cat command which details some of the common usages of cat that are often overlooked. These are known as the so called Useless Uses of cat (UUOC).

Example

Many unknowing command line users will use the cat command without realizing that they can accomplish the same goal using redirection techniques instead.

For instance, passing the content of a file to the standard input (stdin) of another command can be done like so.

cat filename | command arg1 arg2 argn

This can be done with redirection as well.

command arg1 arg2 argn < filename

Explanation

The first example, with cat, passes the data in filename using a Unix pipe. A subprocess is spawned in order to pass the output along as a stream of data through stdin of the second command.

In the second example, the stdin file descriptor accessible in the program is replaced with a file descriptor to filename, using the dup series of system calls. This allows full access to the file instead of a stream of data as is the case with using pipes.

The benefit of using redirection over pipes, in general, is that the file is directly opened using a file descriptor and can be fully accessed. This might not be an apparent issue in the case above. But some commands may access stdin in ways that obviously benefit from having a direct descriptor to the file.

For instance, the following example will benefit from having direct access since tail will utilize seek to efficiently find the end of the file.

fallocate -l 1G large_file.txt

time bash -c "cat large_file.txt | tail -c 8 -"

real    0m0.494s
user    0m0.027s
sys     0m0.768s

time tail -c 8 < large_file.txt

real    0m0.002s
user    0m0.002s
sys     0m0.000s

Conclusion

Both pipelines and redirections are highly useful tools in the Unix toolchain. The Useless Uses of cat are acknowledgments not meant to put down or discourage users. But are instead used to educate users on the benefits and usages of both.

Happy hacking!