truncate: Set a File to an Exact Size
truncate -s N sets a file to exactly N bytes, extending with sparse zero bytes or cutting off the excess.
For a fixture of a specific size, an empty file, or a sparse large file to test disk-quota handling, truncate sets the size directly without writing every byte.
What it does
truncate sets a file to a given size. Growing a file adds a sparse hole of zero bytes (fast, uses little disk); shrinking discards the tail. -s 0 empties a file in place. Relative forms +N/-N adjust from the current size. Part of coreutils.
Common usage
# make a 1 GiB sparse fixture instantly
truncate -s 1G sparse.img
# empty a log without deleting/recreating it
truncate -s 0 app.log
# grow a file by 4 KiB
truncate -s +4K data.bin
# match one file's size to another
truncate -r reference.bin target.binOptions
| Flag | What it does |
|---|---|
| -s <n> | Set size to n (K/M/G suffixes allowed) |
| -s +<n> / -<n> | Grow / shrink relative to current size |
| -c, --no-create | Do not create the file if it is missing |
| -r <file> | Use another file's size as the target |
| -o | Treat the size as blocks, not bytes |
In CI
Use truncate -s 0 file to reset a log between test phases without changing its inode, so a tail -f or an open handle keeps working. Sparse files from truncate -s 1G are ideal for disk-full and quota tests since they cost almost no real space until written.
Common errors in CI
"truncate: cannot open f for writing: Permission denied" means the file or directory is not writable. "truncate: Invalid number: 1GB" means a bad suffix; use 1G (or 1GB only where documented, but stick to K/M/G). A sparse file created with truncate reports its full size with ls -l but little with du, which can confuse size-based assertions; check du --apparent-size if you meant the logical size.