Truncate is a command used to resize the file to the size you require. It helps you to delete the content inside a file without removing that file. Basically, this command helps to truncate a file quickly and easily. The truncated file depends on the current file size; if the file size is larger than the specified size, the extra data will be lost.
Here at LinuxAPT, as part of our Server Management Services, we regularly help our Customers to perform related Linux system commands queries.
In this context, we shall look into how to use the truncate command in Linux.
If your system doesn't have a truncate command, for Ubuntu/ Debian system, it is provided by the coreutils package.
To Install Coreutils Packages, Run the apt command:
$ sudo apt install coreutils
After installation, You can use the grep command to see the detail of packages:
$ dpkg -l | grep coreutils
Truncate command takes the following format:
$ truncate -s SIZE filename
Now, we will take a look at some truncate command with examples.
1. Clear the content of the file
To do this, run the following command:
$ truncate -s 0 filename
We will use du command to check the disk space used:
$ du -sh filename
To clear the content of "filename.txt" file, run the command:
$ truncate -s 0 filename.txt
Then will use du command to check again:
$ du -sh filename.txt
You can use the ls -lh command to check file size:
$ ls -lh filename.txt
2. Truncate a file to the desired size
We will use du command to check the disk space used:
$ du -sh filename
If the original size of filename.txt file is 4.0KB.
Now we will truncate the file to 400 bytes size:
$ truncate -s 400 filename.txt
Use the ls -lh command to check file size:
$ ls -lh filename.txt
3. Increase or decrease file size
You can use the prefix "+" or "-" with -s option to do this.
If you are working with a file, let's say dup.txt and its size is 400k, then we will try increasing 600k bytes:
$ truncate -s +600k dup.txt
Then check the file:
$ ls -lh dup.txt
Similarly, you can use the prefix "-" with -s option to decrease file size.
4. Get help
You will see this option if you run the command below:
$ truncate --help
5. Check your version
Now, to check the version of truncate in the system, run the command:
$ truncate --version
This article covers how to use the truncate command in Linux. The safest method to empty a log file in Linux is by using the truncate command. Truncate command is used to shrink or extend the size of each FILE to the specified size.