Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to shrink or extend the size of a file in Linux?
The truncate command is used to shrink or extend the size of a file to a specified size in Linux. Unlike deletion commands, truncate cannot remove files but can modify their contents and size. When reducing file size, if the specified size is smaller than the actual size, the extra data will be permanently lost.
Syntax
The general syntax of the truncate command is as follows:
truncate OPTION... FILE...
Options
Brief description of options available in the truncate command:
| Option | Description |
|---|---|
-c, --no-create |
Do not create any files if they don't exist |
-o, --io-blocks |
Treat size as number of IO blocks rather than bytes |
-r, --reference=RFILE |
Set size of file to match the reference file |
-s, --size=SIZE |
Set size of the file to SIZE bytes |
--help |
Display help information and exit |
--version |
Output version information and exit |
Common Use Cases
Emptying a File
To remove all contents of a file and set its size to zero bytes:
truncate -s 0 file.txt
This command empties the file completely while preserving the file itself.
Creating Files with Specific Size
If the specified file doesn't exist, truncate will create a new file with the given size:
truncate -s 200K file.txt
This creates a 200KB file named file.txt in the current directory.
Preventing File Creation
To prevent creating new files when they don't exist, use the -c option:
truncate -c -s 200K file.txt
If file.txt doesn't exist, no new file will be created and the command will fail silently.
Examples
Extending File Size
To extend a file to 1MB (padding with null bytes):
truncate -s 1M document.txt
Using Reference File
To make one file the same size as another:
truncate -r reference.txt target.txt
Checking Available Options
To view all available options and usage information:
truncate --help
Size Specifications
The truncate command supports various size units:
| Unit | Description | Example |
|---|---|---|
| B | Bytes (default) | truncate -s 1024B file.txt |
| K | Kilobytes (1024 bytes) | truncate -s 10K file.txt |
| M | Megabytes (1024K) | truncate -s 5M file.txt |
| G | Gigabytes (1024M) | truncate -s 2G file.txt |
Conclusion
The truncate command is a powerful tool for file size management in Linux. It can efficiently shrink files by removing excess data or extend them by padding with null bytes. Always use caution when shrinking files as data loss is permanent and irreversible.
