Bash_Scripts/Cron/Autodelete-Files.bash
2021-08-05 18:02:16 -05:00

88 lines
1.7 KiB
Bash
Executable File

#!/bin/bash --posix
set -e
DIRECTORY=""
HOUR=12
DAYS_OLD=3
usage() {
printf "%s\n" "Usage: Autodelete-Files -d <path>
--directory <dir> | -d <dir>
Example:
--directory ~/trash/
--hour <int < 24> | -h <int < 24>
Example:
--hour 5
Default: 12
--days-old <int > 0> | -o <int > 0>
Example:
--days-old 3
Default: 3"
}
error() {
printf "\n%s\n" "$1" >&2
exit 1
}
confirmation() {
while true; do
read -p "${1}" -n 1 -r choice
case "$choice" in
y|Y ) return 1;;
n|N ) return 0;;
* ) echo -e "\nInput must be either y, Y, n, or N";;
esac
done
}
while :; do
case $1 in
-h | -\? | --help)
usage # Display a usage synopsis.
exit
;;
--) # End of all options.
shift
break
;;
-d | --directory)
shift
DIRECTORY="${1}"
;;
-h | --hour)
shift
HOUR="${1}"
;;
-o | --days-old)
shift
DAYS_OLD="${1}"
;;
-?*)
printf 'Unknown option: %s\n' "$1" >&2
usage
error
;;
*) # Default case: No more options, so break out of the loop.
break ;;
esac
shift
done
[[ "${DIRECTORY}" == "" ]] && error "A directory must be provided!"
[[ -d "${DIRECTORY}" ]] && error "The given directory ${DIRECTORY} was invalid"
[[ "${HOUR}" -gt 23 ]] && error "Hour may be no more than 23"
[[ "${HOUR}" -lt 0 ]] && error "Hour may be no less than 0"
[[ ! "${HOUR}" -eq "${HOUR}" ]] && error "Hour must be a number"
[[ ! "${DAYS_OLD}" -eq "${DAYS_OLD}" ]] && error "Days-old must be a number"
NEW_CRON_ENTRY="00 ${HOUR} * * * find ${DIRECTORY} -mtime +${DAYS_OLD} -exec rm {} \;"
crontab -l | { cat; echo "${NEW_CRON_ENTRY}"; } | crontab -