PSA: Stop Abusing the cat Command and Let Cats Be Cats
PSA about abuse of cat(1) command. Don't abuse cats
I'm sharing a public service announcement to stop the unnecessary abuse of the cat command in shell scripts. Piping a single file through cat spawns an extra process that does nothing but copy bytes to a program that can already read the file itself. Tools like grep, wc, head, and awk can open files directly. Let's be humane and let cat do what it was designed for: concatenating multiple files.
Piping a single file through cat spawns an entire process whose only job is to copy bytes to a program that already knew how to read them.
- internet2000
> Piping a single file through cat spawns an entire process whose only job is to copy bytes to a program that already knew how to read them.
Chrome probably spawned two processes when I cmd+clicked this into a new tab. It really doesn't matter.
- jasongi
The beauty of cat is that streams are the universal interface.
Program A might accept a file as the last positional arg. Program B might accept it as a named arg, where the name/flag could be anything from --input or -f or --file etc.
But a program will read from STDIN, which all good unix programs do, then piping cat into it works every time. I can write the cat foo.txt part before I even know what command I'm piping it into.
- lifthrasiir
Don't do this:
cat file | wc -l => wc -l < file
cat file | head -n 5 => head -n 5 file
cat file | awk '{print $1}' => awk '{print $1}' file
cat file | sort => sort file
Do this instead:
cat file | wc -l => <file wc -l
cat file | head -n 5 => <file head -n 5
cat file | awk '{print $1}' => <file awk '{print $1}'
cat file | sort => <file sort
The front-cat abuse is all about the order. The effective solution needs to keep the relative order of arguments.
- MPSimmons
Unless you're executing these commands in a loop over a large number of items, or the item itself is gargantuan, it's almost always harmless.
Personally, when I'm exploring, I build a command line iteratively. Cat the file to see the content, pipe to grep to get the lines I want, sed/awk/cut/etc to finagle from there.
- jmclnx
In this day an age this is still making rounds ? So this is the memory usage of cat on my system:
VSZ RSS SZ CMD
3252 1608 813 /bin/cat
To me there are far more things to worry about than cat. How about your multi-gig browser for one ?
Now for firefox:
VSZ RSS SZ CMD
3472212 395968 868053 /usr/lib64/firefox/firefox
Maybe people should be looking at that ? I will not even get into modern Linux Desktops :)