12

Is it safe to use a bash script and a cronjob to empty /tmp automatically, or should I do this differently?

0

2 Answers 2

14

/tmp is cleaned on every system reboot, but for systems that cannot be rebooted often, and specially if the only objective is to clean /tmp a script can be made to clean it.

No process should keep important data there but it is important that you are able to clean /tmp without disrupting any processes writing data in tmp.

I recommend to use tmpreaper for that.

You can install it with sudo apt-get install tmpreaper.

From the man page:

tmpreaper recursively searches for and removes files and empty directories which haven't been accessed for a given number of seconds. Normally, it's used to clean up directories which are used for temporary holding space, such as "/tmp". Please read the WARNINGS section of this manual.

Usage normally involves invoking tmpreaper in /tmp with a time spec argument. The time spec argument can be anything from d for days, h for hours, m for minutes, or s for seconds.

Please use the --test to dry run and get an output of the results before you actually run the command. That will get you an idea of what will be deleted before you actually commit any changes to the file system.

3
  • Thank you! To fully answer my question, can you explain me why this is better than using a simple recursive remove? Mar 7, 2014 at 22:07
  • 1
    Its not, its just simpler to use and the arguments used are more understandable. A simple rm -rf on a list of files returned by find would do the job also. This is "just another way", not even saying is the best one, just the one I use on the servers I setup. Mar 7, 2014 at 22:34
  • tmpreaper seems like a good tool, worth using --test and --showdeletes when testing.
    – RichVel
    Sep 28, 2016 at 16:26
6

Try adding a cronjob which executes

find /tmp/* -type d -mtime +5 -print0 | xargs -0 rm -rf 
find /tmp/* -type f -mtime +5 -print0 | xargs -0 rm -rf 

This would delete all files older than 5 days.

1
  • There's no point passing -r to the rm command in the second example, which is only finding files anyway, right?
    – Bobby Jack
    Jun 22, 2021 at 10:30

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .