Most efficient method to empty the contents of a file

I am aware of three methods to delete all entries from a file.

They are

  • >filename
  • touch filename1
  • filename < /dev/null

Of these three I abuse >filename the most as that requires the least number of keystrokes.

However, I would like to know which is the most efficient of the three (if there are any more efficient methods) with respect to large log files and small files.

Also, how does the three codes operate and delete the contents?


1Edit: as discussed in this answer, this actually does not clear the file!

Asked By: debal

||

Actually, the second form touch filename doesn’t delete anything from the file – it only creates an empty file if one did not exist, or updates the last-modified date of an existing file.

And the third filename < /dev/null tries to run filename with /dev/null as input.

cp /dev/null filename works.

As for efficient, the most efficient would be truncate -s 0 filename (see here).

Otherwise, cp /dev/null filename or > filename are both fine. They both open and then close the file, using the truncate-on-open setting. cp also opens /dev/null, so that makes it marginally slower.

On the other hand, truncate would likely be slower than > filename when run from a script since running the truncate command requires the system to open the executable, load it, and then run it.

Answered By: ash

Other option could be:

echo -n > filename

From the man page of echo:

-n Do not print the trailing newline character.

Answered By: Arturo Herrero

There is a builtin command “:”, which is available in sh,csh,bash and others maybe, which can be easily used with the redirecting output operator > truncate a file:

#!/usr/bin/env bash
:> filename

What I like on this is, that it does not need any external commands like “echo” etc.

One big advantage of truncating files instead of deleate/recreate them is, that running applications which works with this file (e.g. someone makes an tail -f filename or a monitoring software, …) don’t have to reopen it. They just can continue using the filedescriptor and gets all the new data.

Answered By: Mirko Steiner
Categories: Answers Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.