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:
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:
if [ -r sulog.1 ]; then
mv -f sulog.1 sulog.2
if [ -r sulog.0 ]; then
mv -f sulog.0 sulog.1
if [ -r sulog ]; then
mv -f sulog sulog.0
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.