김진창
김진창

Reputation: 105

Is there a way to automatically delete files in the tmp folder?

Is there a way to automatically delete files with the thumb extension in the tmp folder when Ubuntu's capacity has exceeded 80 percent or one month later?

Should I use crontab? Or should I write crontab and shellscript at the same time?

Upvotes: 0

Views: 1203

Answers (1)

paxdiablo
paxdiablo

Reputation: 881393

It seems to me you can just use the standard method of deleting files based on age, with a slight modification to reduce the threshold if the filesystem is too full.

The normal method for deleting all *.thumb files in /tmp over a certain age (about a month) is with a command like:

find /tmp -type f -name '*.thumb' -mtime +30 -delete

So, all you need to do is to reduce the threshold is to modify the mtime test under some circumstance. To do this based on how full the file system is could be done with something like:

#!/usr/bin/env bash

# Default to about a month.

thresh=30

# Get percentage used of /tmp, needs to match output of df, such as:
#  Filesystem     1K-blocks      Used Available Use% Mounted on
#  tmp              1000000    280000    720000  28% /tmp

tmppct=$(df | awk '$6=="/tmp" { gsub("%", "", $5); print $5 }')

# Reduce threshold if tmp more than 80% full.

[[ ${tmppct} -gt 80 ]] && thresh=1

# Go and clean up, based on threshold.

find /tmp -type f -name '*.thumb' -mtime +${thresh} -delete

The only possibly tricky bit of that script is passing the output of df (based on format specified) through:

awk '$6=="/tmp" { gsub("%", "", $5); print $5 }'

This will simply:

  • look for lines where the sixth field is /tmp;
  • remove the trailing % from the fifth field; and
  • finally output that (modified) fifth field to capture the percentage full.

Then just create a crontab entry that will run that script periodically.

Upvotes: 1

Related Questions