Skip to content

Instantly share code, notes, and snippets.

@tb3088
Created October 5, 2017 19:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tb3088/f6397fdf5ffc2ebce2ccb41fe69174ad to your computer and use it in GitHub Desktop.
Save tb3088/f6397fdf5ffc2ebce2ccb41fe69174ad to your computer and use it in GitHub Desktop.
purge a directory structure of 'old' files
#!/bin/bash
[ -x "${FIND:=`which find 2>/dev/null`}" ] || { echo "ERROR: 'find' program ($FIND) not found/executable"; exit 1; }
PROG=`basename $0 .sh`
declare -i VERBOSE=0 MAXDEPTH=1 DRYRUN=0
let ${AGET:=atime}
let ${AGE:='+1'}
# Directories, files (default)
OPTIONS="dm:no:qrt:vx:"
while getopts ${OPTIONS} arg; do
case $arg in
# atime is not appropriate for directories
d) DO_DIRS=1; AGET=mtime ;;
m) MAXDEPTH=$OPTARG ;;
n) EVAL="echo" ;;
o) AGE="$OPTARG" ;;
# '-q' doesn't log non-fatal errors
q) unset VERBOSE ;;
r) unset MAXDEPTH ;;
t) AGET="$OPTARG" ;;
v) let $((VERBOSE++)) ;;
x) EXTRA+=" $OPTARG" ;;
*) echo "WARN: unknown arg '-${arg}'";;
esac
done
CMD="${FIND} . -xdev ${MAXDEPTH+-maxdepth $MAXDEPTH} ${EXTRA} -$AGET $AGE"
FILECMD="$CMD -type f -delete"
DIRCMD="$CMD -type d ! -name \. -execdir rmdir ${VERBOSE+-v} {} \;"
# clear out handled options
shift $((OPTIND-1))
while [ -n "$1" ]; do
DIR=$1
if [ ! -d "${DIR:?}" ]; then
[ -n "${VERBOSE}" ] && echo "NOTICE: not a directory ($DIR)"
else
[ ${VERBOSE:-0} -gt 0 ] && echo "${PROG} ${DIR}"
(
# Yes, excessive paranoia
set -e
cd "$DIR" || exit
[ ${DO_DIRS:-0} -eq 1 ] && ${EVAL:-eval} "$DIRCMD" || ${EVAL:-eval} "$FILECMD"
)
fi
shift
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment