Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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

They are

  • >filename
  • touch filename
  • 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?

share|improve this question
2  
What about truncate -s 0 filename? –  moose Jun 29 at 16:18

1 Answer 1

up vote 14 down vote accepted

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: http://linux.die.net/man/1/truncate.

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 the run it.

share|improve this answer
1  
So why do you say that truncate is the most efficient? –  Stéphane Chazelas Aug 30 '13 at 6:24
1  
The truncate operation uses the ftruncate() or truncate() system call which does not bother to open the file. It also avoids the close() system call that cp and > filename methods need to call. –  ash Aug 30 '13 at 6:26
2  
Actually, it (at least the GNU one) does an open+ftruncate+close (in addition to the many system calls it does to load and initialise itself), as anyway, it would have to create the file if it didn't exist and truncate(2) doesn't do that. –  Stéphane Chazelas Aug 30 '13 at 8:01
    
If we use touch filename, will the inode remain same (provided there was a file before)? –  pMan Aug 30 '13 at 8:30
    
@pMan yes, you can try it and check with ls -i –  terdon Aug 30 '13 at 13:02

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.