2

I have a cron job that writes logs to /tmp. I want to automatically delete the oldest files when the free space in the disk becomes less than 1GB.

I'm trying to do df -ah /tmp, then take the 2nd line, use cut to get the avail column. Then in a for loop, keep deleting the files older than n days with -mtime until there's enough free space.

I probably want to set this up as a cron job that runs daily as well.

  • I'm trying to do df -ah /tmp, then take the 2nd line, use cut to get the avail column. Then in a for loop, keep deleting the files older than n days with -mtime. Until there's enough free space. – yasith Sep 22 '15 at 15:37
  • 1
    You should put that in your question, you can edit it. So you have a concept and tried to make a script that uses it, right? Include that script too. – gronostaj Sep 22 '15 at 15:38
  • Apart from bash scripting, are you sure this will be enough? For instance, currently I have 96K in my /tmp, which is much smaller than 1G, the remaining free space. It is probably a better idea to run apt-get autoremove && apt-get clean && apt-get autoclean to regain some free space. – MariusMatutiae Sep 22 '15 at 16:39
  • If you're running Debian or a derivative of it, you may consider using tmpreaper: it does precisely what you're looking for. – Jaap Eldering Nov 21 '15 at 19:49
1

Instead of a find -mtime, do an ls -t, for example:

DIR=/tmp
FREESPACE=1000000
find $DIR -type f | xargs ls -1rt | while read f ; do
  if [ `df --output=avail $DIR | tail -1` -ge $FREESPACE ] ; then
    break
  fi
  # rm -f $f
done

Uncomment the rm -f $f to have it actually work...

However, I typically would do things a little differently. I'd put my cron logs in /var/log and let something like logrotate handle managing disk space. Or as another alternative, I'd put the logs into a separate subdirectory such as /tmp/mycronjob/*, and then keep a fixed number of days of log files. It's not as flexible as monitoring disk space, but it's also a straight forward find /tmp/mycronjob -mtime +30 -exec rm {} \; and more predictable.

  • 1
    I think the rm -f should be after the conditional. Otherwise it will always delete at least 1 directory even if there's enough available space. – Morgan Christiansson Oct 6 '17 at 15:17
  • @MorganChristiansson true. – TOertel Oct 7 '17 at 17:35
  • Parsing ls is flawed in general. – Kamil Maciorowski Oct 7 '17 at 18:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.