WillSquire
8/11/2015 - 11:02 AM

Clean unused images - Clears images that have been un-accessed in the last 30 days inside Drupal's `/sites/default/files/styles/` directory

Clean unused images - Clears images that have been un-accessed in the last 30 days inside Drupal's /sites/default/files/styles/ directory in Drupal's root. Script must be placed in Drupal's root /scripts directory to function

#!/bin/sh

#
# Clean unused images
# ===================
# Cleans unused images that have not been accessed in the last 30 days from the image styles
# cache. (Works using a relative location from Drupal's `scripts` directory, which is where
# this script should be placed to function).
#
# @author Will Squire <will_squire@hotmail.co.uk>
#

#
# Usage
# -----
# To run this script, either use `sh script_file_name.sh` or (if marked at executable) use:
#
# `./script_file_name.sh`
#
# If this script appears with a "Permission denied" message on execution attempt, ensure the
# script has been made executable with:
#
# `chmod +x script_file_name.sh`
#
# Setup
# -----
# To have this script run autonomously at regular intervals it's recommended that a cron
# daemon is setup to invoke this execution at given times. To do this:
#
# - First ensure that the file is prepared for execution by cron (see above) and that the
#   script's permissions are set to the appropriate user and/or group. If they are not,
#   change ownership with:
#
#   `chown <user>:<group> /path/to/script/file.sh`
#
# - Next open up a crontab. Note that a crontab can be setup on a specific unix user account
#   (although not the recommended method) with the command:
#
#   `crontab -e`
#
# - In this file add a cron time first (`* * * * *` runs every minuate of every hour of every
#   day of every month on any weekday, whilst `0 0 * * *` runs at zero minuate of zero hour
#   each day, and so on) and then the command to execute after this on the same line. Because
#   this script has been crafted to execute relative to the files it must alter, cron must
#   use either $BASH_SOURCE to get the path of this script's directory and work out the
#   relative path from there (ideally), or if that isn't possible make sure cron changes the
#   current directory to this script's directory before execution. If the latter, the
#   following line is an example of how to setup the cron and change directory before
#   execution:
#
#   `* * * * * cd /path/to/drupal/root/scripts && sh script_name_to_execute.sh`
#

BASEDIR=$(dirname $BASH_SOURCE)

# Delete files that were not accessed in the last 30 days
find "$BASEDIR/../sites/default/files/styles/" -type f -atime +30 -delete
# Change -delete for -print to see what files would be deleted