Truncate a file from the command line

Here’s a hack to truncate a file (such as a log) in Linux and Windows. First, let’s cover some related commands. In Linux to create an empty file, run:

touch /tmp/foo

However, touching a existing file doesn’t change its length. To delete a file run this command:

rm -f /tmp/foo

You could combine these two commands to delete and recreate a file, but that’s not precisely truncating a file:

rm -f /tmp/foo
touch /tmp/foo

How about to simply truncate a file (clear the contents and set the size to zero) in a single command? Easy:

echo > /tmp/foo

While on a low-level this trick is not either precisely equivalent to the ftruncate() system call, it generally produces the same effect. Truncating is useful to clear log files (such as system logs in /var/log/). I used it to programmatically clear the GNOME 2.26 recent documents list in Ubuntu 9.04 (Jaunty Jackalope). In older GNOME versions, you could simply delete ~/.recently-used.xbel, but GNOME 2.26 caches recently used documents in memory unless you run:

echo > ~/.recently-used.xbel

To truncate a file to a certain size (say 1024 bytes), check out dd.

In Microsoft Windows, truncating a file is similar:

echo.> c:\foo

The period immediately after the command echo is essential. While on Linux (with POSIX) the truncation is 0 bytes, on Windows the similar hack truncates the file to 2 bytes.

On Windows the following creates a zero byte file:

echo|set /p=>c:\foo

2 thoughts on “Truncate a file from the command line

  1. In fact on Linux your echo trick will also fail, as echo by default adds a line break. To truncate to zero bytes, you need:
    echo -n > foo
    to suppress the line break.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s