# Set up a cron job to delete log files every day



## Delta_X7

I'm new to cron. I have an Ubuntu 8.04 server and I would like to set up a cron job to delete the contents of /var/log everyday. How would I go about doing this?


----------



## lensman3

Something like

5 * * * * /bin/rm -f /var/log/* 2>&1 /dev/null

This will run 5 minutes after midnight, once a day. The -f flag is to force removal. See "man 5 crontab" for a lot more options. To edit the crontab file as root: first "su" to root, then enter "crontab -e". You can change crontabs editor by changing the "EDITOR" environment variable.

There are subdirectories in /var/log. You will probably have to individually clean those out also. 

It also might be better instead of removing the file, recall that a program/daemon somewhere has those files already open, so you might have to truncate them instead of deleting them. To truncate the file use: "cp /dev/null <filetotruncate>". 

Take a look at the /etc/cron.daily directory. This already does what you want. I think Linux rolls the log files over once a week. Why don't you just fix cron.weekly so that that happens once a day! Take a look at /etc/logrotate file. I think this can be tweaked so that logs will rotate once a day.

Good luck.


----------



## Delta_X7

Thanks for the reply. Great info. 
I'll try editing the cron file and changing it to happen once a day.
Thanks for the help.


----------



## gurgel

lensman3 said:


> 5 * * * * /bin/rm -f /var/log/* 2>&1 /dev/null


Rewrite this line to:

5 * * * * /bin/rm -f /var/log/* > /dev/null 2>&1

Else you will delete the file /dev/null, since there is no redirect to it, just a copy from stderr to stdout!

Also, descriptor-copies (2>&1) must occur AFTER normal redirection, else its effect will not be as supposed. 

Have a look at this example:

bos$ (echo i am on stderr 1>&2) > /dev/null
i am on stderr
bos$ (echo i am on stderr 1>&2) 2>&1 > /dev/null
i am on stderr
bos$ (echo i am on stderr 1>&2) > /dev/null 2>&1
bos$


----------



## lensman3

Good point. Except I have been deleting /dev/null for about every 4 hours for ten years! And I run a keepalive.sh script that tests my Internet hookup every minute. All output gets flushed except those times the network is down and then I get an email.

The crontab 8 man page says that:



Code:


[Several environment variables are set up automatically by the cron(8) daemon.  SHELL is set  to  /bin/sh,  and  LOGNAME  and  HOME  are  set  from  the /etc/passwd line of the crontab´s owner.  HOME and SHELL may be overridden by settings in the crontab; LOGNAME may not./CODE]

So my question is: Does /bin/sh behave the way the bash does?  That must be why I occationally get a file called "2" in CWD!


----------

