How to create a temporary storage directory that automatically deletes contents after X days (Mac)

Here's a quick way to have a directory that allows you to store files and other subdirectories for temporary usage. For example, I use this to save all my downloads and other files that I only need for the next day or two.

We first need to create a new cron job. If you're not familier with cron, it's basically instructions to the cron daemon of the general form: "run this command at this time on this date". (or for some light reading) We're going to use cron to run a command to move all the contents of a directory to the trash.

// from the terminal enter to create new crontab or open existing
crontab -e

// next press Esc+i to enter into "INSERT" mode which will allow you enter text
00  */2  *  *  *  find /path/to/temp/ -mtime +1 -exec mv {} ~/.Trash ; >/dev/null 2>&1

// then save the crontab by pressing Esc, :, w, q (write & quit)

Now let's explain what's going on with the cron job.

00 minutes (ie: 2:00,18:00)
*/2 every 2 hours
* * * every hour, day of the month, day of the week
find /path/to/temp/ finds all contents of directory
-mtime +1 where the file's make time is X days more than current date
-exec mv {} take all contents found from find comment and executes the mv (moves) command
~/.Trash ; users trash can (could be any directory though)
>/dev/null 2>&1 suppresses any output from displaying (ie fulling up your users mailbox)

Also, if you're looking for a quick way to add extra storage to your Macbook, checkout the Nifty Drives. This is what I use for my temporary storage.


comments powered by Disqus