How to Shrink and Extend File Sizes Using the truncate Command in Linux

When you are managing a high-performance Linux database server, you often need to create massive, completely empty placeholder files (known as “sparse files”) to reserve physical space on the hard drive for future data dumps. Conversely, you might have a gigantic, bloated log file that you need to aggressively chop down to a smaller size without entirely deleting the file or breaking the application that is actively writing to it. To instantly alter the physical byte size of any file on your system, you must use the truncate command.

How to Shrink an Existing File

If you have an incredibly bloated 50 GB Apache access log (e.g., access.log) that is threatening to fill up your entire root partition, you can use the truncate command to instantly chop the file down to a highly manageable size.

To violently shrink the file down to exactly 10 Megabytes, use the -s (size) flag:

truncate -s 10M access.log

The command executes in a fraction of a millisecond. It completely destroys any data located beyond the 10 MB boundary, permanently erasing it from the hard drive. However, unlike using the rm command to delete the file, the actual access.log file structure remains perfectly intact, meaning the Apache web server will continue writing new logs to it without crashing.

How to Empty a File Completely

If you want to keep the file but completely destroy 100% of the data inside it, you can simply set the size parameter to absolute zero.

truncate -s 0 access.log

This is often vastly superior to opening the file in a text editor (like nano or vim) and manually deleting millions of lines, which could cause a lower-end server to run out of RAM and crash.

How to Create Massive Placeholder Files

The truncate command can also expand files. If you point the command at a file that does not exist, it will instantly create it.

To create a massive, completely empty 100 Gigabyte placeholder file instantly, run:

truncate -s 100G massive_database.img

Because the command creates a “sparse file,” it does not actually write 100 GB of zeroes to your physical hard drive (which would take hours and physically wear down an SSD). Instead, it manipulates the filesystem metadata to report the file as being 100 GB in size, executing the command in less than a second while cleanly reserving the logical space for future operations.

Get the best tech tips delivered straight to your inbox.

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