Stop Using rm! 5 Pro Ways to Quickly Clear Log Files in Linux

Published: 2026-07-18
Author: DP
Views: 1
Category: Linux
Content
In daily Linux server administration (for example, maintaining web services for wiki.lib00.com), dealing with oversized log files is a common challenge. A beginner's instinct is often to delete the log file using the `rm` command and recreate it with `touch`. ## Why shouldn't you just use `rm` to delete log files? If you delete a log file that is currently being written to by an application (like Nginx, MySQL, or your custom app on lib00), the disk space won't be released immediately because the application still holds the file descriptor. Furthermore, the service won't be able to write to a newly created file with the same name until the service is restarted. The most elegant solution is to **empty the file content** without changing its inode or file descriptor. Here are 5 professional methods summarized by DP to quickly clear Linux log files: --- ## 1. Shell Redirection (Most Recommended & Fastest) This is the simplest and fastest method, working perfectly in most mainstream shells (like Bash, Zsh, etc.). ```bash > wiki.lib00.log ``` --- ## 2. Using `:` or `true` Command The `:` is a shell built-in null command that produces no output, equivalent to `true`. Combined with redirection, it clears the file instantly. ```bash : > wiki.lib00.log # OR true > wiki.lib00.log ``` --- ## 3. Using `cat /dev/null` This is a traditional approach favored by veteran Linux users. It overwrites the target file with the empty content from the system's black hole device `/dev/null`. ```bash cat /dev/null > wiki.lib00.log ``` --- ## 4. Using the `truncate` Command Semantically, this method is the most explicit. The `truncate` command is specifically designed to shrink or extend the size of a file. The `-s 0` flag sets the file size to exactly 0 bytes. ```bash truncate -s 0 wiki.lib00.log ``` --- ## 5. Sudo Solutions for Restricted Permissions If your current user lacks write permissions for the log file, running `sudo > wiki.lib00.log` will result in a `Permission denied` error. This happens because the redirection is executed by your current shell, not by `sudo`. Instead, use one of these workarounds: ```bash # Option A: Using tee (Recommended) true | sudo tee wiki.lib00.log > /dev/null # Option B: Using truncate sudo truncate -s 0 wiki.lib00.log # Option C: Invoking sh to execute the command sudo sh -c "> wiki.lib00.log" ``` --- ## Summary & Best Practices by DP@lib00 * **Daily manual operations:** Simply use `> filename` for maximum efficiency. * **Automation scripts:** `truncate -s 0 filename` is highly recommended for its clear semantics and maintainability. * **Permission restrictions:** Opt for `sudo truncate -s 0 filename`.
Related Contents