In order to clean a log file, some users simply delete the old file and create a new log file. There are however many ways to remove the content of the log file without having to open it. Make sure not to clear the content of a critical system or configuration file since this might lead to a system crash or failure.
The first alternative would be to run the command :
cat /dev/null > logfile
cp /dev/null logfile
dd if=/dev/null of=logfile
Where in the last command, ‘if’ refers to the input file while ‘of’ to the output file.
The /dev/null device file is a rather special file that removes any input stream that was redirected to it.
true | tee logfile
In general when writing :
a_task | tee -a logfile
It will put the output into logfile and to stdout.
The echo command can be used with an empty string and redirected to the file as follows:
echo “” > logfile
echo > logfile
An empty string is not to be confused with null since a string is an object with no attributes or parameters within it. For those who develop in C++ or Java know already that Null means that an object does not exist.
When you run the echo command above, the file will contain an empty line. In order to redirect a null output to the file, you could rely on the -n switch which commands echo to not output a trailing newline.
echo -n “” > logfile
How to empty a file in linux using truncate
Another way would be to use :
truncate –size 0 logfile [linux clear log file]
The truncate command shrinks or extends the size of a file to a desired size.
It can be used it with the -s switch to indicate the file size. To empty a file content therefore, you could specify a size of 0 (zero) as shown in the command above.
In order to perform this for multiple files, you can proceed as follows :
truncate -s 0 logfile1 logfile2 … [empty log file linux]
Given the fact that logfiles can be useful, you could archive a copy by compressing and then saving it. You could rely in this case on logrotate, which can carry this out easily. For more on logrotate, refer to the this link.
Can can also use a loop :
for f in logfile1 logfile2 … ; do
# select your desired command to empty the file
That would be all for now folks. In this article we have provided few methods to help clear or empty a log file (or any other file) using simple command line tools and shell redirection utilities.If you know other alternatives, please feel free to write them in the comments section.
If you like the content, we would appreciate your support by buying us a coffee. Thank you so much for your visit and support.