Emptying a unix/mac-osx/linux log file

 

Recently i had to empty a log file in a Linux machine. It had been a while since i did that and i had forgotten how simple it was… remembering my college years and the first time i had a unix system in my hands i thought i should write this to remind me the early days.

To empty a log file (to all young grasshoppers) …. (another reference to how old i am….that is a line from the original “kung fu” series) in a safe way without deleting the file you could run the following commands :

cat /dev/null > messagesFile   (where messagesFile is the name of your file)

cat-ing the null device into the file is preferable to deleting the file because in some cases the subsystem wont recreate the log file if it doesnt exist. Also its preferable to rm followed by touch because file ownerships and permissions remain correct.

If you want to retain a small part of the current logging information use tail as the example underneeth:

cd /var/adm

tail -100 sulog > tmp

cat tmp > sulog

A third approach is to keep several old versions of a log file on the system by periodically deleting the oldest one, renaming the cuurent one and recreating it.The script below keeps the last three versions of the sulog file in addition to the current one:

#!/bin/sh

cd /var/adm

if [ -r sulog.1 ]; then

  mv -f sulog.1 sulog.2

fi

if [ -r sulog.0 ]; then

  mv -f sulog.0 sulog.1

fi

if [ -r sulog ]; then

  mv -f sulog sulog.0

fi

cat /dev/null > sulog

 

Run the script each week via cron and you are all set to keep the last month’s worth of sulog files.

 

Advertisements


Categories: Linux, Mac OSX, Programming, Servers

Tags: , ,

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

%d bloggers like this: