#!/bin/sh
#
#David Klein
#04-16-2013
#
# This script is run by a nightly crontab. It keeps the last $KEEP releases and deletes the rest. Otherwise we'll run out of space!
#
KEEP=3


### START

# Do some testing to make sure it looks like we are in a directory that has a current and releases folder
if [ -z $1 ] || [ ! -d $1 ]
then
echo "Error parsing arguments. Try \"cleanup-old-releases.sh PROJECT_BASE_DIR\""
exit
fi

BASEDIR=$1
DIR=$1\/releases
if [ -d $DIR ] && [ -d $BASEDIR\/current ]
then
# Go to the directory we want to remove files from
cd $DIR

# Get a file count and only look for directories matching a specific pattern.
FILES=`ls -cl | awk '{print $9}' | grep -e '[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]' -c`

# Test if there are more files than the number that we want to keep.. stop if there are less
if [ $FILES -gt $KEEP ]
then
REMOVE=`expr $FILES - $KEEP`
echo 'I found '$REMOVE' items to remove from '$DIR'!'
for item in `ls -cl | awk '{print $9}' | grep -e '[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]' | head -n $REMOVE`; do rm -rf $DIR/$item; done
else
echo 'There was nothing to remove from '$DIR'.'
fi
else
echo 'I did not find a "current" AND "releases" directory... are you running this script from the root directory of the project ?'
fi

  • This script is "/media/data/cleanup-old-releases.sh"
  • Then I have a crontab entry for each project

@daily cd /media/data; /bin/sh cleanup-old-releases.sh /media/data/www/rails/project1

@daily cd /media/data; /bin/sh cleanup-old-releases.sh /media/data/www/rails/project2

@daily cd /media/data; /bin/sh cleanup-old-releases.sh /media/data/www/rails/project3