How to Shrink and Extend Files Using the truncate Command in Linux

When you are managing a massive Linux web server, you will frequently encounter highly aggressive log files that swell to dozens of gigabytes in size, threatening to completely fill up the hard drive partition. You cannot simply delete the active log file, because the background web server software is currently holding the file open; if you delete it, the server will crash because it has nowhere to write its data. To instantly shrink the massive log file back down to zero bytes without breaking the connection to the running server, you must use the truncate command.

How the truncate Command Works

The truncate command is a dedicated file manipulation utility. Instead of deleting a file entirely, it mathematically shrinks (or expands) the physical size of the file on the hard drive to an exact, predefined dimension.

To safely shrink a massive, 50-gigabyte active log file down to absolute zero bytes (effectively emptying the file while leaving the empty shell completely intact for the server to continue writing to), use the -s (size) flag and specify 0:

truncate -s 0 access.log

The command executes instantly. The file size drops to zero bytes, the hard drive space is instantly recovered, and the active web server software never even notices the file was altered.

Shrinking to a Specific Size

If you are trying to email a database dump file to a colleague, but your email provider enforces a strict 25-Megabyte attachment limit, you can use truncate to forcefully shrink the file to fit the requirement (though be warned, this will physically delete the data located at the very end of the file).

To shrink a file to exactly 25 Megabytes, run:

truncate -s 25M database.sql

The command supports a variety of standard mathematical suffixes for precision:

  • K (Kilobytes)
  • M (Megabytes)
  • G (Gigabytes)

Extending a File (Creating Sparse Files)

Interestingly, truncate can also be used in reverse. If you run the command and request a size that is vastly larger than the file currently is, Linux will artificially extend the file by injecting empty, invisible “null” bytes.

For example, if you want to create an empty, artificial 10-Gigabyte file (perhaps to test how a backup script handles transferring massive files over the network), you do not need to wait hours for the system to generate gigabytes of random text data. Simply run:

truncate -s 10G massive_test_file.bin

This command instantly creates what is known as a “sparse file.” The system registers the file as being exactly 10 Gigabytes in size, but because it is completely empty, it takes less than a second to create and consumes virtually zero actual physical space on your SSD.

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.