You’ll often find yourself in situations where you need to empty a file. So, how do you empty a file in Linux? How to clear a file from all of its content without deleting the actual file?
There are several ways you can delete all the content of a file without actually deleting the file. Let’s see various ways of emptying a file in Linux:
6 ways to empty a file in Linux
The simplest way to empty a file is to use the command below. If the file is not in use, it will work in Bash:
While the above works only in Bash Shell, you can use a similar command for other shells:
: > filename
You can also clear a file using the truncate command:
truncate -s 0 filename
Another way to empty a file is via echo command:
echo -n > filename
You can also use the famous /dev/null:
cat /dev/null > file.log
And if you don’t have enough permissions for any of the above commands, this is the sure shot but a little dirty way to achieve it:
touch newfile mv newfile filename
I hope this quick tip helped you to clear a file in Linux. Do bookmark us for more Linux quick tips.