Shell: empty or truncate a file
Shell commands to empty an existing file (truncate, redirection) or replace it with an empty file, and how they differ.
Several ways to empty an existing file, or to create an empty file, from the shell.
Truncate an existing file
| Command | Effect |
|---|---|
truncate -s 0 filename |
Sets the size to 0 bytes (GNU coreutils truncate). The file keeps its inode and permissions. |
:> filename |
Truncates the file (redirects the empty output of :). |
> filename |
Same as above. |
true > filename |
Same as above (true produces no output). |
cat /dev/null > filename |
Same, using /dev/null as an empty input. |
Caution: echo > filename and echo "" > filename write a newline (1 byte), so the file is not empty. Use :> filename instead.
Replace with a new empty file
touch newfile
mv newfile filename
The original file is replaced by a new one (new inode). A process that still holds the old file open keeps writing to the old inode, which no longer has a name.