13 October 2022

As a support engineer, it is a good habit and maybe even a company policy to delete customer logs downloaded to local PCs/laptops once they are no longer needed. Instead of doing this manaually periodically, you can set up a cron job similar to the following to do that.

SHELL=/bin/bash
LOG_DIR=/Users/lungang.fang/Downloads
LOG_DAYS=15

# At 12:30pm Mon-Fri, delete files/dirs older than 15 days and create/update timestamp file "LOG_PURGE"
30 12 * * 1-5 find $LOG_DIR -mtime +$LOG_DAYS \( -type f -or \( -type d -empty \) \) -delete && date > $LOG_DIR/LOG_PURGE

Note:

  • This is my implementation of @josh.allan's idea.
  • Disclaimer: the above source code of cron job is just an example. Modify, test and apply it at your own risk.
  • Although launchd appears to the recommended approach to schedule jobs in MacOS, cron meets our needs perfectly, so just use it for simplicity.
  • For cron jobs to work in MacOS, cron must be granted full disk access (see this post for how to do that).
  • The job is not scheduled at midnights because, unlike servers, laptops are most likely sleeping at that time.
  • I didn't discard stderr (i.e. find ... 2>/dev/null) because I do prefer getting a system mail in such cases.
  • Create a file named LOG_PURGE in the log directory mainly to remind myself that such a cron job exists.
  • Do not delete non-empty folders even if they are old because subfolders or files may be new.


blog comments powered by Disqus