Master the Linux ‘truncate’ Command: A Comprehensive Guide

Peter Hou
2 min readMay 20, 2023

--

The truncate command is a powerful tool in a Linux environment for managing file sizes. This guide covers its history, usage, parameters, common use cases, and some clever techniques for its application. It is important for beginners to learn this command as it is widely used in managing systems.

Instructions

This article aims to provide a complete guide for beginners to understand and master the truncate command in Linux. From its history to its common use cases, every aspect of this command will be thoroughly covered.

History

The truncate command is a standard Unix command that is primarily used to shrink or extend the size of each FILE to the specified size.

When and why to use it

The truncate command is very handy when you need to quickly shrink or expand the size of a file without needing to open, modify, or save it manually. It's a low-level command that directly manipulates the file size.

How to use it

The general syntax of the truncate command is as follows:

$ truncate OPTIONS... SIZE FILE...

The commonly used parameters

  • -s, --size=SIZE set or adjust the file size by SIZE.
$ truncate -s 20K myfile.txt
  • -c, --no-create do not create any files that do not exist.
$ truncate -c -s 0 myfile.txt

Other supported parameters

  • -o, --io-blocks: Treat SIZE as the number of IO blocks of the file rather than bytes.
  • -r, --reference=RFILE: Base the size on the size of RFILE.

Most common use cases

One common use case of truncate is to clear log files without deleting them. This can be useful in production systems.

$ truncate -s 0 /var/log/mylogfile.log

The tricky skills

truncate can be used in combination with other commands. For example, you can use it with find command to clear all .log files:

$ find . -name "*.log" -exec truncate -s 0 {} \\\\;

What needs to be noted

One important point to note is that the truncate command doesn't work on directories. It can only manipulate regular files.

Conclusion

Mastering the truncate command can help manage file sizes efficiently and effectively in a Linux environment. The ability to quickly manipulate file sizes can prove useful in many situations, particularly when dealing with log files or other files where the size can change over time.

--

--

Peter Hou

I am a Senior Software Engineer and tech lead in a top tech company.