Skip to content

Instantly share code, notes, and snippets.

@boynoiz
Last active January 29, 2021 07:22
Show Gist options
  • Save boynoiz/0a6e27738eb08b57eb0fec105d89beb7 to your computer and use it in GitHub Desktop.
Save boynoiz/0a6e27738eb08b57eb0fec105d89beb7 to your computer and use it in GitHub Desktop.
#!/bin/bash
set -e
function help() {
cat << EOF >&2
Usage : ./smooth_del.sh <dir> <ext> <day(s)> <quiet (optional)>
<dir> : The path of directory eg. /var/log/something_log/
<ext> : The extension of file to delete eg. jpg
<day(s)> : Amount number of the day eg. 14 mean 2 weeks
--q <quiet> : The script will work in quiet mode
EOF
exit 1
}
function del() {
# Temporary file to store file names
NOW=$(date +"%m-%d-%Y")
FILE_FILENAMES="/tmp/file_list_${NOW}"
while true; do
# Get all filename and directory then save in temporary text file
find ${FOLDER} -type f -mtime +${OLDER} -name "${EXTENSION}" -ls | head -5000 | awk '{print $11}' > ${FILE_FILENAMES}
# Count total file (from number of text line)
COUNT_FILES=$(wc -l "${FILE_FILENAMES}" | awk '{print $1}')
echo "The total file is ${COUNT_FILES}"
# If text line more than 0
if [[ ${COUNT_FILES} -gt 0 ]]; then
printf "[%s] %s files found. going on with removing\n" "$(date)" "${COUNT_FILES}"
if [[ -s ${FILE_FILENAMES} ]]; then
while read FILE; do
echo "${FILE}"
rm "${FILE}"
sleep 1
done < "${FILE_FILENAMES}"
fi
else
printf "[%s] script has finished, almost all files have been deleted" "$(date)"
break
fi
sleep 5
done
}
# Check if user pass --help or empty argument
if [[ ${1} == "--help" ]] || [[ ${1} == "" ]]; then
help
fi
# Define variable from argument
FOLDER=${1}
EXTENSION=${2}
OLDER=${3}
QUIET=${4}
# Test Directory
if [[ ! -z ${FOLDER} ]] && [[ ! ${FOLDER} =~ [\/]$ ]]; then
FOLDER="${FOLDER}/"
elif [[ ! -z ${FOLDER} ]] && [[ ! -d ${FOLDER} ]]; then
echo "The directory does not exist, Please check and try again."
exit 1
fi
# Test Extension
if [[ ! -z ${EXTENSION} ]] && [[ ${EXTENSION} =~ ^[a-zA-Z0-9]+ ]]; then
EXTENSION="*.${EXTENSION}"
else
echo "The extension is invalid."
exit 1
fi
# Test days
if [[ ! -z ${OLDER} ]] && [[ ! ${OLDER} =~ ^[0-9]+ ]]; then
echo "The number of day(s) is invalid"
exit 1
fi
# If quiet mode exist
if [[ ! -z ${QUIET} ]] && [[ ${QUIET} == "--q" ]]; then
del
elif [[ -z ${QUIET} ]]; then
read -p "You want to delete all ${EXTENSION} files that older than ${OLDER} day(s) in ${FOLDER}, Do you want to continue? (y/n)" QUESTION
if [[ ${QUESTION} =~ ^([nN][oO]|[nN])+$ ]]; then
echo "See ya!"
exit 1
elif [[ ${QUESTION} =~ ^([yY][eE][sS]|[yY])+$ ]]; then
del
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment