## 15.2. Instead of Removing a File, Empty It

Sometimes you don't want to remove a file completely -- you just want to empty it:

- If an active process has the file open (not uncommon for log files), removing the file and creating a new one will not affect the logging program; those messages will just keep going to the file that's no longer linked. Emptying the file doesn't break the association, and so it clears the file without affecting the logging program.

- When you remove a file and create a new one with the same name, the new file will have your default permissions and ownership (Section 50.3). It's better to empty the file now, then add new text later; this won't change the permissions and ownership.

- Completely empty files (ones that ls -l says have zero characters) don't take any disk space to store (except the few bytes that the directory entry (Section 10.2) uses).

- You can use the empty files as "place markers" to remind you that something was there or belongs there. Some Unix logging programs won't write errors to their log files unless the log files already exist. Empty files work fine for that.

- Empty files hold a "timestamp" (just as files with text do) that shows when the file was last modified. I use empty files in some directories to remind me when I've last done something (backups, printouts, etc.). The find -newer (Section 9.8) command can compare other files to a timestamp file.

Well, you get the idea by now.

How can you empty a file? Watch out: when some editors say that a file has "no lines," they may still append a newline character when writing the file. Just one character still takes a block of disk space to store. Here are some better ways to get a properly empty file:

- In Bourne-type shells like sh and bash, the most efficient way is to redirect the output of a null command:

  >     $ > afile

- If the file already exists, that command will truncate the file without needing a subprocess.

- Copy the Unix empty file, /dev/null (Section 43.12), on top of the file:

  >     % cp /dev/null afile

- Or just cat it there:

  >     % cat /dev/null > afile

You can also "almost" empty the file, leaving just a few lines, this way:

`tail` Section 12.8

>     % tail afile > tmpfile
>     % cat tmpfile > afile
>     % rm tmpfile

That's especially good for log files that you never want to delete completely. Use cat and rm, not mv -- mv will break any other links to the original file (`afile`) and replace it with the temporary file.

-- JP

Copyright © 2003 O'Reilly & Associates. All rights reserved.