Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/bin/bash
- #
- # Settings
- #
- # Prevents the script to continue running when one command fails
- set -e
- # set -x
- # Enabling extended syntax (useful for excluding files in rm commands)
- shopt -s extglob
- #
- # Functions
- #
- # Prints help message
- function usage {
- echo "This program allows you to delete files according to a pattern, in the given directories, by excluding the directories defined by the user."
- echo "Arguments:"
- echo -e " -h\t\t\tPrints this help message"
- echo -e " -p <pattern>\t\tThe pattern that will be used to delete the files"
- echo -e " -d directory1[,...]\tA comma separated list of directories in which to delete the files based on the pattern"
- echo -e " -e directory1[,...]\tA comma separated list of the directories to exclude"
- echo -e " -o n{smhdw}\t\tOnly the files older than n seconds, n minutes, etc will be deleted."
- echo
- echo "The arguments -p and -d are mandatory."
- }
- # Deletes the files in the given directory and its subdirectories
- # $1: pattern
- # $2: directory in which files must be deleted based on the pattern
- # $3: excluded directories
- function rm_in_subdirs {
- local pattern=$1
- local dir=$2
- cd $dir
- exclusion=""
- if [ ! -z "$EXCLUDED" ]; then
- local excluded=( `echo "$EXCLUDED"` )
- echo "Excluded dirs: ${excluded[@]}"
- exclusion="-path ./${excluded[0]}"
- for excluded_dir in "${excluded[@]:1}"
- do
- exclusion="$exclusion -o -path ./$excluded_dir "
- done
- fi
- if [ -z "$MTIME_ARG" ]; then
- mtime=""
- else
- mtime="-mtime +$MTIME_ARG"
- fi
- if [ -z "$exclusion" ]; then
- find . -type f -name "file*.txt" $mtime | xargs rm
- else
- find . \! \( \( $exclusion \) -prune \) -type f -name "file*.txt" $mtime | xargs rm
- fi
- }
- #
- # Handling command line option
- #
- while getopts d:e:p:o:h option
- do
- IFS=','
- case "$option" in
- d)
- read -ra DIRECTORIES <<< "$OPTARG"
- ;;
- e)
- read -ra EXCLUDED_DIR <<< "$OPTARG"
- ;;
- p)
- export PATTERN=$OPTARG
- ;;
- o)
- # output date format: to comply with touch -t option
- export MTIME_ARG=$OPTARG
- ;;
- h)
- usage
- exit 0
- ;;
- esac
- unset IFS
- done
- echo "Directories : ${DIRECTORIES[@]}"
- echo "Excuded ones: ${EXCLUDED_DIR[@]}"
- echo "Pattern : $PATTERN"
- echo
- # If one of the mandatory params is not present: print help, leave the program.
- if [ -z $PATTERN ] || [ -z $DIRECTORIES ]; then
- usage
- exit 1
- fi
- #
- # Deleting the files.
- #
- for directory in "${DIRECTORIES[@]}"
- do
- export EXCLUDED=${EXCLUDED_DIR[@]}
- rm_in_subdirs $PATTERN $directory
- done
- echo "done"
- unset EXCLUDED
- unset PATTERN
- unset MTIME_ARG
Add Comment
Please, Sign In to add comment