Delete Old Log Files with Linux Shell

One of the most needed system administration tasks can be surprisingly difficult to do well. Old log files should be deleted or cleaned up to keep the number of files and disk space used manageable. Here is an example using typical tools found on the Linux command line (shell). An assumption here is that your log files are named so that a standard “sort” command will list them in order from oldest to newest (and a reverse sort will list from newest to oldest). My previous post on date format for log file names should help if you need hints with a log file name style to use.

myLogDir=~
keepLessThan=11
find $myLogDir -maxdepth 1 -name '*_explog.txt' \
 | sort -r | tail -n +$keepLessThan | xargs -r rm
# this will keep the newest 10 log files matching
# ... '*_explog.txt' in the directory ~ (user's home)
# the variables are not necessary, just used for the example

If you need to handle spaces in file names, try piping through tr '\n' '\0' before using the special xargs -0 option for processing null separated file names.

Advertisements

About notesbytom

Keeping technology notes on WordPress.com to free up my mind to solve new problems rather than figuring out the same ones repeatedly :-).
This entry was posted in Linux, System Administration and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s