The so-called Useless use of cat has been one of the perennial memes of Unix culture going back years, at least long enough to warrant inclusion on cat's Wikipedia page.
However, like all dogmas, there are times when using cat isn't useless—even when it's not being used for it's "canonical" purpose, con-cat-enating files together.
I am prompted to write this as I'm writing a shell script that can operate on standard input or on a file given on the command line. This is a common idiom, used in nearly every common utility that I can think of. So how to do it in shell when not using one of these utilities that will do it "for free?"
To my mind, the easiest way would be to use cat:
cat "${1:--}" |
while read -r line; do
# ...
done
Since cat can take -
as an argument meaning "use standard input,"
this use of cat uses $1
if it exists, or defaults to reading from
standard input. Simple!
addendum
I suppose one could argue the above is a useful use of cat, and that the advice to avoid useless uses stands. While there are other, perhaps *technically better* ways to pass input to some other process in shell, I offer these points to consider:
- Using cat in these "useless" instances is rarely harmful
- Using cat can be more readable than invoking arcane redirection syntax
- While using cat will start another process, if you're writing performance critical shell code, you have other problems
Thus concludes my thoughts on the taboo against so-called "Useless use of cat."