IO Redirection – Difference Between Cat and ‘>’ to Zero Out a File

catio-redirection

Are these two commands any different on how they go about zero-ing out files? Is the latter a shorter way of doing the former? What is happening behind the scenes?

Both

$ cat /dev/null > file.txt

$ > file.txt 

yield

-rw-r--r--  1 user  wheel  0 May 18 10:33 file.txt

Best Answer

cat /dev/null > file.txt is a useless use of cat.

Basically cat /dev/null simply results in cat outputting nothing. Yes it works, but it's frowned upon by many because it results in invoking an external process that is not necessary.
It's one of those things that is common simply because it's common.

Using just > file.txt will work on most shells, but it's not completely portable. If you want completely portable, the following are good alternatives:

true > file.txt
: > file.txt

Both : and true output no data, and are shell builtins (whereas cat is an external utility), thus they are lighter and more 'proper'.

 

Update:

As tylerl mentioned in his comment, there is also the >| file.txt syntax.

Most shells have a setting which will prevent them from truncating an existing file via >. You must use >| instead. This is to prevent human error when you really meant to append with >>. You can turn the behavior on with set -C.

So with this, I think the simplest, most proper, and portable method of truncating a file would be:

:>| file.txt
Related Question