LinuxCommandLibrary

truncate

TLDR

Set a file to a specific size (creates if doesn't exist)

$ truncate -s [100M] [file]
copy
Empty a file (set size to zero)
$ truncate -s 0 [file]
copy
Shrink a file by a specific amount
$ truncate -s -[10K] [file]
copy
Extend a file by a specific amount
$ truncate -s +[50M] [file]
copy
Set file to same size as another file
$ truncate -r [reference_file] [target_file]
copy
Create a sparse file of a specific size
$ truncate -s [1G] [sparse_file]
copy

SYNOPSIS

truncate [-c] [-o] -s SIZE FILE...
truncate [-c] [-o] -r RFILE FILE...

DESCRIPTION

truncate shrinks or extends the size of each FILE to the specified size. If a FILE does not exist, it is created. If a FILE is larger than the specified size, the extra data is lost. If a FILE is shorter, it is extended with zero bytes (creating a sparse file on most filesystems).
The command is useful for creating test files of specific sizes, clearing log files without deleting them (preserving permissions and ownership), and creating sparse files for disk image allocation or database pre-allocation.
When truncating a file, data beyond the new size is permanently lost. When extending, the file becomes a sparse file where the extended portion doesn't actually consume disk space until data is written to it.

PARAMETERS

-s SIZE, --size=SIZE

Set or adjust file size to SIZE bytes
-c, --no-create
Do not create files that don't exist
-o, --io-blocks
Treat SIZE as number of IO blocks instead of bytes
-r RFILE, --reference=RFILE
Use RFILE's size as the reference size
--help
Display help information
--version
Display version information

SIZE SUFFIXES

SIZE may be specified with the following suffixes:
K - Kilobytes (1024 bytes)
M - Megabytes (1024 K)
G - Gigabytes (1024 M)
T - Terabytes (1024 G)
KB - 1000 bytes
MB - 1000 KB
GB - 1000 MB
SIZE may also be prefixed with + to extend or - to shrink by that amount.

CAVEATS

Truncating a file being written to by another process can cause data corruption or application errors. The -s 0 operation is faster than rm followed by touch for clearing files while maintaining ownership and permissions. Sparse file behavior depends on the filesystem; not all filesystems support sparse files. Extended regions read as zeros but may consume actual space on copy to non-sparse-aware systems.

HISTORY

The truncate command is part of GNU Coreutils and has been available on Linux systems for many years. The underlying ftruncate() system call has been part of POSIX since the beginning, but the command-line utility provides convenient access to this functionality. On BSD systems, a similar truncate command exists with slightly different syntax. The GNU version became the standard on most Linux distributions.

SEE ALSO

dd(1), fallocate(1), touch(1), stat(1), rm(1)

Copied to clipboard