The Dangers of Deleting Log Files
When running an Ubuntu Linux server, background services (like Apache, Nginx, or MySQL) constantly write data to dedicated log files inside the /var/log/ directory. Over several months, a single error log can bloat to dozens of gigabytes, consuming your entire hard drive and crashing the server. The obvious solution seems to be simply typing rm error.log to delete the massive file. However, this is incredibly dangerous. The web server process still holds an active, open file descriptor pointing to that exact inode. If you delete the file while the server is running, the operating system cannot reclaim the disk space, and the service will eventually crash because it has nowhere to write new errors. Instead of deleting the file, you must cleanly empty its contents while keeping the file itself intact.
Using the truncate Command
The safest and fastest way to empty a massive text file without breaking the file descriptor is to use the truncate command.
- Open your Terminal application or log into your server via SSH.
- Navigate to the directory containing the massive file (e.g.,
cd /var/log/nginx/). - Type the following command:
sudo truncate -s 0 error.log - Press Enter and provide your administrator password.
How the Command Works
sudoprovides the necessary root permissions to modify system log files.-s 0stands for “size zero.” This explicitly tells the operating system to shrink the file’s binary footprint to exactly zero bytes.
The command executes instantly, even on a 50GB file. Because the file name, permissions, ownership, and underlying inode never change, the Nginx service doesn’t even notice what happened. It will simply continue writing the very next error to line 1 of the newly emptied file, and your hard drive space is instantly recovered.