How to clean log file?

Is there a better way to clean the log file? I usually delete the old logfile and create a new logfile and I am looking for a shorter type/bash/command program. How can I use an alias?

Asked By: Micromega

||
> logfile

or

cat /dev/null > logfile

or

true | tee logfile

(fell free to substitute false or any other command that produces no output, like e.g. : does in bash) if you want to be more eloquent, will all empty logfile (actually they will truncate it to zero size).

If you want to know how long it “takes”, you may use

dd if=/dev/null of=logfile

(which is the same as dd if=/dev/null > logfile, by the way)

You can also use

truncate --size 0 logfile

(or truncate -s 0 logfile) to be perfectly explicit or, if you don’t want to,

rm logfile

(in which case you are relying on the common behaviour that applications usually do recreate a logfile if it doesn’t exist already).

However, since logfiles are usually useful, you might want to compress and save a copy. While you could do that with your own script, it is a good idea to at least try using an existing working solution, in this case logrotate, which can do exactly that and is reasonably configurable.

Should you need to do it for several files, the safe way is

truncate -s 0 file1 file2 ...

or

> file1 > file2 ...

Some shells (zsh) also allow one to specify several redirection targets.

This works (at least in bash) since it creates all the redirections required although only the last one will catch any input (or none in this case). The tee example with several files should work in any case (given your tee does know how to handle several output files)

Of course, the good old shell loop would work as well:

for f in file1 file2 ... ; do
    # pick your favourite emptying method
done

although it will be much slower due to the command being run separately for each file. That may be helped by using find:

find <criteria matching required files> 
    -exec <command capable of zeroing several files> {} +

or

find <criteria matching required files> -delete
Answered By: peterph
Categories: Answers Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.