When you are testing backup scripts or evaluating how a specific application handles out-of-disk-space errors, you often need a massive, multi-gigabyte file to fill up a hard drive. Using the dd command to physically write 50GB of zeroes to a disk is incredibly slow and causes unnecessary wear on Solid State Drives (SSDs). If you simply need a file to report a specific byte size to the filesystem, you must use the truncate command.
How the truncate Command Works
The truncate utility does not physically write blocks of data to the storage platter. Instead, it interacts directly with the filesystem’s metadata (the index). It tells the filesystem, “Pretend this file is exactly 10 Gigabytes.” The file is instantly created as a “sparse file.” It reports a 10GB size to all software (including the ls command), but it physically consumes zero bytes of actual disk space until real data is written into it.
How to Shrink or Expand a File to an Exact Size
To use the command, you must use the -s (size) flag followed by your target file size.
To instantly create a brand new, empty file that the system believes is exactly 50 Gigabytes, run:
truncate -s 50G massive_test_file.bin
Because it only edits the metadata, the command finishes in less than a millisecond. You can use standard suffixes like K (Kilobytes), M (Megabytes), G (Gigabytes), and even T (Terabytes).
If you point truncate at an existing file that already contains real data, it will forcefully alter the size of that file.
- Expanding: If you have a 1GB log file and run
truncate -s 5G logfile.txt, the command will append 4GB of empty “zeroes” to the end of the file, instantly swelling it to 5GB. - Shrinking (Data Destruction): If you have a 5GB log file and run
truncate -s 1G logfile.txt, the command acts like a guillotine. It instantly chops off the last 4GB of the file. That data is permanently destroyed and cannot be recovered.
How to Quickly Empty Log Files
Because it shrinks files instantly, system administrators frequently use truncate to empty massive, out-of-control log files without having to delete the file itself (which would require restarting the logging service to recreate the file).
To instantly reduce a 100GB Apache web server error log down to zero bytes without breaking the application, run:
sudo truncate -s 0 /var/log/apache2/error.log
The file remains in place with all its original permissions, but its contents are instantly vaporized.