Website Vidya
Linux & ServersStep-by-Step Guide

How to Truncate Files in Linux: truncate & Redirection

Learn truncate files in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

RR
Rajesh RayLead Systems Educator
Published:
10 min read
PDF Cheat Sheet
How to Truncate Files in Linux: truncate & Redirection
AI Executive SummaryWebsiteVidya AI

10 min read

Learn truncate files in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

Key Highlights
  • What truncate Does and When to Use It
  • Availability and Installation Across Linux Distributions
  • Command Syntax, Arguments, and Exit Status Codes
Grounded in full engineering runbookWebsiteVidya AI Engine

Managing disk capacity on active production servers often requires administrators to truncate files in linux without restarting active services. When a database log, application debug log, or web server access file unexpectedly balloons to tens of gigabytes, simply deleting the file with rm can worsen the situation: running processes maintain their open file descriptors, keeping disk space occupied while hiding the file from view.

Truncating a file shrinks or expands its byte length to a specified size without altering its filesystem inode number, directory link, ownership, or permission mode bits. The active daemon holding an open file descriptor continues writing sequentially to the emptied file without crashing or requiring a restart.

Linux provides several methods to truncate files: the dedicated GNU truncate utility, shell redirection (such as : > file), the fallocate tool, and dd. Understanding when and how to truncate files is a vital operational skill for production incident response and log rotation.

Advertisement
How to Truncate Files in Linux: truncate & Redirection — syntax, flags, and practical terminal workflow diagram
How to Truncate Files in Linux: truncate & Redirection — command syntax, key options, and production workflow reference.

What truncate Does and When to Use It

At the kernel level, file truncation is implemented via the truncate(2) or ftruncate(2) system call. When a file is truncated to zero bytes, the Linux Virtual File System (VFS) updates the inode's i_size field to 0 and invokes the filesystem's block deallocation routines. The filesystem driver (such as ext4 or XFS) deallocates all associated physical extents/blocks and marks them as free in the block allocation bitmap, immediately reclaiming storage space.

Because the file's directory entry and inode table entry remain untouched, any running process that opened the file with the O_APPEND flag (standard for logging daemons) seamlessly continues writing to the file. Future writes will append at the new end-of-file (byte 0). Conversely, if truncate -s is used to expand a file to a larger size, the kernel creates a sparse file: the inode records the new apparent size without physically writing zero blocks to disk until real data is written.

At the operating system level, truncate (distributed in coreutils) interfaces with the Linux kernel through standard C library system calls and virtual filesystems. Understanding how truncate resolves file descriptors, kernel structures, and exit status codes helps system administrators predict performance on high-load production servers.

Availability and Installation Across Linux Distributions

The truncate utility is packaged in coreutils across mainstream Linux distributions. It is pre-installed on standard Ubuntu, Debian, RHEL, Rocky Linux, AlmaLinux, Fedora, and Arch Linux systems, while minimal container images may require manual installation:

Advertisement

Before running administrative tasks or automation scripts, verify whether truncate is installed and inspect which binary path and version your shell resolves:

type -a truncate
truncate --version 2>/dev/null || man -f truncate

# Illustrative output (reviewed against documentation)
truncate is /usr/bin/truncate
truncate (coreutils)
# Debian / Ubuntu
sudo apt-get update && sudo apt-get install -y coreutils

# RHEL / Rocky / AlmaLinux / Fedora
sudo dnf install -y coreutils

# Arch Linux
sudo pacman -S --noconfirm coreutils

# Alpine Linux
sudo apk add --no-cache coreutils

Command Syntax, Arguments, and Exit Status Codes

truncate -s 0 FILE... | truncate -s SIZE FILE... | : > FILE

The primary syntax for the core utility is truncate [OPTION]... --size=SIZE FILE.... The -s (--size) argument specifies the target byte length. It accepts integer byte numbers or standard SI/IEC suffixes such as K, M, G, T (power of 1024).

The SIZE parameter also supports relative modifiers: +SIZE extends the file by the specified amount, -SIZE reduces the file by that amount, shrinks to at most the specified size, and >SIZE expands to at least that size. The -c (--no-create) flag instructs truncate not to create a new file if the target does not already exist.

  • 0 — All specified files were truncated or extended successfully.
  • 1 — Operational failure, such as write permission denied or read-only filesystem.
  • 2 — Malformed syntax, invalid size argument, or missing operand.

Important Options and Flags Reference

Option / FlagLong Form / ArgumentTechnical Behavior and Purpose
-s <SIZE>--size=<SIZE>Sets or adjusts the file size to the specified byte length (e.g. 0, 10M, 1G).
-c--no-createDo not create any files that do not already exist.
-o--io-blocksTreats SIZE as the number of I/O blocks rather than bytes.
-r <RFILE>--reference=<RFILE>Sets file size to match the size of reference file RFILE.
: > FILEShell Built-inNull command redirection; empties file to zero bytes instantly in bash/sh.
> FILEShell RedirectionBare redirection; truncates file to zero bytes (standard POSIX shells).
true > FILECommand RedirectionRuns true built-in and redirects empty stdout to truncate file.

The choice between truncate -s 0 file.log and shell redirection : > file.log usually depends on privileges and automation environments. Shell redirection (> file.log) is faster and built into every shell, but cannot be easily combined with sudo (running sudo : > file.log fails because the redirection is performed by the unprivileged shell before sudo launches).

Advertisement

Using truncate with sudo truncate -s 0 /var/log/syslog works cleanly because sudo executes the binary itself with elevated privileges. Furthermore, truncate -s allows shrinking files to non-zero thresholds (e.g. truncate -s 100M large.log) or creating sparse disk images, which shell redirection cannot achieve.

When combining short flags on the command line, POSIX and GNU utilities allow clustering boolean flags behind a single hyphen, provided any option taking an argument appears last. In automated shell scripts, using long-form GNU options where portable makes self-documenting code that is easier to audit during peer review.

Practical Basic and Advanced Usage Examples

1. Truncate an Active Log File to Zero Bytes with truncate

Empty an oversized log file immediately while preserving its inode and permissions.

echo "Error logs..." > /tmp/app.log
truncate -s 0 /tmp/app.log
ls -l /tmp/app.log

# Illustrative output (reviewed against documentation)
-rw-r--r-- 1 admin admin 0 Oct 22 21:35 /tmp/app.log

The file is instantly truncated to 0 bytes, freeing disk space while leaving the inode open for active writing.

2. Empty a File Using Bash Null Command Redirection (: >)

Use the built-in shell null command (colon) to zero out a file without spawning external binaries.

echo "Data line" > /tmp/buffer.txt
: > /tmp/buffer.txt
stat -c "%s bytes | %n" /tmp/buffer.txt

# Illustrative output (reviewed against documentation)
0 bytes | /tmp/buffer.txt

The ':' built-in does nothing, and the '>' redirection opens the file with O_TRUNC, zeroing it instantly.

3. Truncate a Privileged Root File Using sudo truncate

Empty a system log file owned by root without running into shell redirection permission errors.

sudo truncate -s 0 /var/log/nginx/access.log
ls -l /var/log/nginx/access.log

# Illustrative output (reviewed against documentation)
-rw-r----- 1 www-data adm 0 Oct 22 21:36 /var/log/nginx/access.log

sudo truncate executes with root privileges, zeroing the file cleanly without disrupting Nginx.

4. Create a Large Sparse File Instantly

Create a 10 Gigabyte sparse virtual disk image that occupies zero physical disk blocks initially.

truncate -s 10G /tmp/disk.img
du -h /tmp/disk.img
ls -lh /tmp/disk.img

# Illustrative output (reviewed against documentation)
0	/tmp/disk.img
-rw-r--r-- 1 admin admin 10G Oct 22 21:37 /tmp/disk.img

The inode records an apparent size of 10G, but physical storage is 0 blocks until actual data is written.

5. Shrink a File to a Maximum Size Threshold

Use the '<' relative modifier to ensure a file does not exceed 50 Megabytes.

truncate -s '<50M' /tmp/data_cache.bin

If data_cache.bin was larger than 50M, it is truncated to 50M; if smaller, it remains untouched.

6. Zero Out a File Using dd as a Universal Fallback

Use dd to truncate a file on legacy or minimal environments where truncate is unavailable.

dd if=/dev/null of=/tmp/legacy.log 2>&1

# Illustrative output (reviewed against documentation)
0+0 records in
0+0 records out
0 bytes copied, 0.0001 s, 0.0 kB/s

Opening the file with /dev/null as input truncates the target file cleanly using standard POSIX utilities.

Real-World Workflows, Pipelines, and Shell Automation

Emergency Disk Recovery: Zeroing Giant Logs Held Open by Daemons

When a partition hits 100% full due to runaway logging and deleting the file with rm fails to free disk space because the daemon still holds it open, use this workflow to identify and truncate open files.

echo "Identifying large deleted or open log files..."
sudo lsof +L1 2>/dev/null | grep -E "log|txt" || true

# Target the active bloated log file
TARGET_LOG="/var/log/app_debug.log"
if [ -f "$TARGET_LOG" ]; then
  echo "Truncating $TARGET_LOG to 0 bytes live..."
  sudo truncate -s 0 "$TARGET_LOG"
  echo "Disk space immediately reclaimed:"
  df -h /var
fi

# Illustrative output (reviewed against documentation)
Identifying large deleted or open log files...
Truncating /var/log/app_debug.log to 0 bytes live...
Disk space immediately reclaimed:
Filesystem      Size  Used Avail Use% Mounted on
/dev/sda2        50G   32G   16G  67% /var

Truncating the file modifies the inode directly; disk blocks are freed immediately by the kernel without restarting the daemon.

Automated Ephemeral Test Log Reset Script

Between automated test runs in a continuous testing pipeline, reset all application log files to zero bytes without losing folder structure or permissions.

LOG_DIR="/var/log/test-suites"
echo "Resetting test logs in $LOG_DIR..."

find "$LOG_DIR" -type f -name "*.log" -exec truncate -s 0 {} +
echo "All log files truncated. Verification:"
find "$LOG_DIR" -type f -name "*.log" -exec stat -c "%s bytes | %n" {} +

# Illustrative output (reviewed against documentation)
Resetting test logs in /var/log/test-suites...
All log files truncated. Verification:
0 bytes | /var/log/test-suites/auth.log
0 bytes | /var/log/test-suites/db.log

find paired with truncate -s 0 {} + resets all log files to zero bytes in high-speed batches.

Pipelines, Redirection, Quoting, and Shell Expansion

When embedding truncate inside shell pipelines (|), conditional chains (&& and ||), or command substitutions ($(...)), the calling shell performs tilde expansion, variable interpolation, and globbing before invoking the binary. Always wrap paths, patterns, and variables in quotes so whitespace and wildcard characters (*, ?) are not expanded prematurely, and use set -euo pipefail in unattended scripts.

Permissions, Security Implications, and Safe Execution

Truncating a file requires write permissions on the file itself. Unlike unlinking (which requires write access on the parent directory), modifying file size via ftruncate(2) directly mutates inode data, requiring the calling process to possess write access to the inode.

Be careful when truncating security audit logs (like /var/log/audit/audit.log). Zeroing audit records destroys forensic evidence of system activity. In compliance environments, log files should be rotated and cryptographically archived rather than truncated.

GNU/Linux, BSD, and BusyBox Implementation Differences

The truncate utility is part of GNU coreutils and FreeBSD, but is not part of the base POSIX.1-2017 utility specification. However, shell redirection (: > file) and dd if=/dev/null of=file are strictly POSIX compliant and universal.

In minimal BusyBox and Alpine Linux environments, truncate is typically included if coreutils is selected, but shell redirection (: > file) remains the most portable method for zeroing files in lightweight shell scripts.

Troubleshooting Common Errors and Diagnostics

sudo : > /var/log/syslog fails with 'Permission denied'

Root Cause: The shell performs the output redirection (>) as your unprivileged user account before sudo executes the ':' command.

Resolution: Use sudo truncate -s 0 /var/log/syslog, or pass the redirection to a root subshell with sudo sh -c '> /var/log/syslog'.

sudo truncate -s 0 /var/log/syslog

truncate: cannot open 'file' for writing: Permission denied

Root Cause: The user lacks write permissions on the targeted file, or the file has the immutable attribute (chattr +i) set.

Resolution: Check file permissions with ls -l, verify file attributes with lsattr, and run with sudo if appropriate.

lsattr file.log
sudo chattr -i file.log && sudo truncate -s 0 file.log

Log file grows back to original huge size immediately after truncate

Root Cause: The application holding the file descriptor does NOT open files with O_APPEND. It maintains an internal byte offset and writes the next line at its previous file position, creating a sparse file with a huge hole.

Resolution: Restart or reload the logging daemon so it resets its internal write file offset back to byte 0.

sudo systemctl restart myapp

Authoritative References and Official Documentation

Frequently Asked Questions

Quick answers to common questions and configurations

4 FAQs
When you delete an open log file with rm, the application holding the open file descriptor continues writing to the unlinked file, keeping disk space occupied while hiding the file from directory listings. Truncating the file keeps the inode intact, instantly frees disk space, and allows the daemon to continue writing without error.
No. Truncating a file alters only its size and modification timestamp. Its inode number, owner, group, and permission mode bits remain unchanged.
The colon (:) is a shell built-in null command that does nothing and returns exit code 0. The redirection operator (>) opens the file with the O_TRUNC flag, clearing its contents to 0 bytes without spawning external processes.
When you expand a file using truncate -s 10G file.img, the kernel records the logical size as 10GB but allocates zero physical storage blocks on disk until data is written. It consumes zero physical disk space initially.
RR
Written byVerified Author

Rajesh Ray

I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.

SPAM-FREE MODERATED DISCOURSE

Join the Conversation & Perspective

Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.

AT
MP
JV
+2

No comments on this guide yet. Be the first to share your thoughts or ask a question!

Recommended Reading10 Guides

Related Technical Guides

Tested runbooks, server administration walkthroughs, and troubleshooting guides

Featured Infrastructure PartnerUp to 75% OFF + 3 Months Free

Supercharge Your Linux & Cloud Workloads with Hostinger

Deploy high-speed NVMe KVM VPS, Docker containers, and LiteSpeed-accelerated WordPress servers in under 60 seconds with full root access, dedicated IPv4, and 24/7 technical support.

Pure NVMe SSD StorageFull Root Access & SSHFree Domain & Unlimited SSL99.9% Uptime SLA
Plans from$2.99/mo
Claim Hostinger DealAffiliate link • Special discount applied at checkout