Sunday, November 03, 2013

Clear files from directory by age

Looping through all directories and files in a directory.

Directories are checked for video files. If found these are moved to the base directory and the directory, and any other files inside is then removed.

Files in base directory are checked for age and removed if older than 90 days.

Update 2014-06-20:
* Added control if we got a directory.
* Added simpler check if we could reach supplied directory or not.
* Removed deluge-console check as it would sometimes hang and wasn't very useful to begin with.

#!/bin/bash

datNow=`date "+%s"`
me=`basename $0`

# check if we got a directory, exit if not
if (( $# != 1 ))
then
  echo "Usage: $me "
  exit 1
fi

# change to directory passed to script, exit if fail
cd $1 || exit 1

for fluff in ./* ; do
  # age in seconds
  datFluff=`date -r "$fluff" "+%s"`

  if [ -d "$fluff" ]; then # fluff is directory
      # diff in minutes
      diff=$((($datNow-$datFluff)/60))

      if [ $diff -gt 60 ]; then
        echo "Moving files: $fluff"
        find "./$fluff/" -type f -regex ".*\.\(mp4\|avi\|mkv\)$" -exec mv {} ./ \;
        echo "Removing    : $fluff"
        rm -r "$fluff"
      fi
  elif [ -f "$fluff" ]; then # fluff is file
    # diff in days
    diff=$((($datNow-$datFluff/86400*86400)/60/60/24)) # diff in days, rounded down 24h.

    if [ $diff -gt 90 ]; then
      echo "Removing      : $fluff // Age: $diff"
      rm "$fluff"
    fi
  fi
done