A script to delete folder later than X days

A script to delete folder later than X days:

#!/bin/bash

if [ $# -lt 2 ]; then
cat <<EOF
  usage:  clean_dir.sh directory_name keey_days
  examples:              
          clean_dir.sh /dump 30   #delete directories old than 30 days in /dump
EOF
  exit 1
fi

CLEAR_DIR=$1
KEEP_DAYS=$2

if [ ! -d "$CLEAR_DIR" ]; then 
  echo "Directory $CLEAR_DIR didn't exist, exit!"
        exit 1
fi

echo "`date` : Start delete directories older than $KEEP_DAYS days in $CLEAR_DIR ar `hostname`"
cd $CLEAR_DIR
find $CLEAR_DIR/* -maxdepth 1 -type d -mtime +${KEEP_DAYS} | awk '{print "ls -ld "$1}'|sh
find $CLEAR_DIR/* -maxdepth 1 -type d -mtime +${KEEP_DAYS} | awk '{print "/bin/rm -rf "$1}' |sh
echo "`date` : End"

In Solaris, replace “-maxdepth 1” with “-prune”

About Alex Zeng
I would be very happy if this blog can help you. I appreciate every honest comments. Please forgive me if I'm too busy to reply your comments in time.

Leave a comment