When I’m working on websites, I often have a need to empty an existing file.
The most common need for this is when looking at error logs. When I’m working on something, I always keep a close eye on the error logs and when I find a problem, I fix it. I then clear the error logs to see if the error reappears. I have no real need to archive or rotate the log. I just want it cleared so next time I open the file, I can see anything that’s new without the need to wade through what was there previously.
It’s very easy to do this, using the truncate command:
truncate -s 0 /path/to/file
If the logged-in user doesn’t have permission to modify the file you’ll need to run the command as the super user:
sudo truncate -s 0 /path/to/file
The truncate command is used to shrink or expand a file to a specified size, and the -s 0 switch tells it to empty the file.
Very useful for situations where you have files like logs where you don’t need to keep the data once you’ve looked at it.