How to clean a log file in Linux/Ubuntu

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.

Using stdout or redirecting to Null

The first alternative would be to run the command :

logfile
or
cat /dev/null > logfile
or
cp /dev/null logfile
or
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.

Using true and tee commands

true | tee logfile

In general when writing :

a_task | tee -a logfile

It will put the output into logfile and to stdout.

Using echo Command

The echo command can be used with an empty string and redirected to the file as follows:

echo “” > logfile
or
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

Read: How to find the largest files on Linux 

Using truncate

Another way would be to use :

truncate –size 0 logfile

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 …

Using logrotate

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.

Read: Guide to Linux Ubuntu/Debian log files for beginners

Using for loop

Can can also use a loop :

for f in logfile1 logfile2 … ; do

# select your desired command to empty the file

done

Conclusion

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.

ziad nahdy

Ziad Nahdy, fan of open source, worked at SAP for 17 years. He is a technical writer, blogger and Linux enthusiast. He loves to read and help others with their problems. He is addicted to open source software but he also loves other technology related stuff.

Leave a Reply

Close Menu