Useless use of cat

“The purpose of cat is to concatenate (or "catenate") files. If it's only one file, concatenating it with nothing at all is a waste of time, and costs you a process.” — Randal L. Schwartz. The following example reads the contents of file twice, once with cat(1), and again with the second program:

$ cat file | wc -l

Eliminate this useless cat via one of the following methods:

$ wc -l < file
$ wc -l file

wc(1) accepts the file either as an argument or standard input; the best method to use depends on the task. For instance, a rare useful use of cat is to count of lines from multiple files:

$ wc -l /etc/passwd
17 /etc/passwd
$ cat /etc/passwd /etc/group | wc -l
48

The useless cat file | syntax may seem attractive when changing the commands following the pipe. However, shells allow the file read before the command, again eliminating the need for the useless cat:

$ <file grep foo
$ <file grep bar

The redirect-before-command syntax fails before while loops in the sh and bash shells (but not zsh). In shells where this fails, the redirect must be done after the while statement. This is one of several reasons I use zsh instead of other Bourne shell derivatives:

$ echo foo > file

$ <file while read l; do echo $l; done
while: not found

bash-2.05a$ <file while read l; do echo $l; done
bash: syntax error near unexpected token `do'

zsh-4.0.4$ <file while read l; do echo $l; done
foo

Back on topic with the useless use of cat, a while read loop can be used in place of a cat something for loop in the shell. Furthermore, a while read loop can be extended to read in additional parameters as needed.

$ for i in `cat input`; do echo $i; done
a
b
c
$ while read i; do echo $i; done < input
a
b
c
$ (echo a b; echo c d) | \
while read one two; do echo $two $one; done

b a
d c

On the other hand, a while loop can interact poorly with some commands, such as ssh.