How to Truncate a File to Zero Bytes in Ubuntu Linux
Managing log files and temporary data often requires clearing content without removing the file itself. This article explains the specific commands used in Ubuntu to truncate a file to zero bytes while preserving its existence and permissions. You will learn the primary utility command and a quick shell method to achieve this efficiently.
Using the Truncate Command
The most direct command for this task is truncate. It is
part of the GNU coreutils package, which is installed by default on
Ubuntu. To set a file size to zero bytes, use the -s flag
followed by 0.
truncate -s 0 filename.txtThis command resizes the file named filename.txt to zero
bytes. The file remains in the directory with its original ownership and
permissions intact.
Using Shell Redirection
A common alternative involves using shell redirection. This method does not require an external command and works in any standard bash shell. Type the greater-than symbol followed by the filename.
> filename.txtAlternatively, you can use the cat command with
/dev/null.
cat /dev/null > filename.txtBoth methods overwrite the existing content with nothing, effectively reducing the file size to zero without deleting the file inode.
Verifying the Result
After running either method, confirm the file size using the
ls command with the -l flag.
ls -l filename.txtThe output should show a size of 0 for the specified file. This ensures the truncation was successful while the file structure remains available for future writes.