Tuesday, May 29, 2007

Delete Old Files

Wanna to delete those old files with a certain extension in some directory, there you go...
#! /bin/sh

if [ $# -ne 3 ]; then
        echo "Usage: $0 <directory> <days old> <extension>"
        exit 1
fi


PATH=/usr/bin:/bin
export PATH


dir="$1"
old="$2"
ext="$3"


if [ ! -d "$dir" ]; then
        echo "Error. $dir does not exist"
        exit 2
fi


find "$dir" -type f -name "*.$ext" -mtime "+$old" -exec rm -i {} \;

If you plan to run that in a cron environment, you will need to remove the "-i" option and discard all the standard output and error to avoid cron from sending you an email. I also include checking to ensure the "old" is an integer greater than 0. The modified script will look like this.

#! /bin/sh

if [ $# -ne 3 ]; then
        echo "Usage: $0 <directory> <days old> <extension>"
        exit 1
fi


PATH=/usr/bin:/bin
export PATH


dir="$1"
old="$2"
ext="$3"



if [ ! -d "$dir" ]; then
        echo "Error. $dir does not exist"
        exit 2
fi
expr $old / 1 > /dev/null 2>&1 && [ $old -gt 0 ]
if [ $? -ne 0 ]; then
        echo "Error. $old is not a number > 0"
        exit 3
fi
 


find "$dir" -type f -name "*.$ext" -mtime "+$old" -exec rm {} \; > /dev/null 2>&1

In Linux, you can specify "-maxdepth" to control descend at most levels. In our case, we need to have an equivalent of "-maxdepth 1" in Solaris. In this blog, it mentioned using "-prune" to simulate this effect. However, I cannot get it working for me.

Alternatively, you can use egrep and xargs to achieve this:

find "$dir" -type f -name "*.$ext" -mtime "+$old" | egrep "^$dir/[^/]+$" | xargs rm

Labels: , ,

0 Comments:

Post a Comment

<< Home