views:

406

answers:

2

I'm writing a script to remove some build artifacts older than 1 week.

The files have names in the form artifact-1.1-200810391018.exe.

How do I go about removing only the files that are greater than 1 week old, excluding the time in hours and minutes at the end of the date-time-stamp?

Currently it is removing all of the files in the directory.

#!/bin/sh

NIGHTLY_LOCATIONS=( "/foo" "/bar" )

ARTIFACT_PREFIX="artifact-*-"

NUM_TO_KEEP=7

for home in $(seq 0 $((${#NIGHTLY_LOCATIONS[@]} - 1))); do
        echo "Removing artifacts for" ${NIGHTLY_LOCATIONS[$location]}

        for file in `find ${NIGHTLY_LOCATIONS[$location]} -name "$ARTIFACT_PREFIX*"`; do

                keep=true

                for day in $(seq 0 $((${NUM_TO_KEEP} - 1))); do
                        date=`date --date="$day days ago" +%Y%m%d`

                        echo $(basename $file ".exe") " = " $ARTIFACT_PREFIX$date

                        if [ "$(basename $file ".exe")" != "$ARTIFACT_PREFIX$date" ]; then
                                keep=false
                        fi
                done

                if [ !$keep ]; then
                        echo "Removing file"
                        rm -f $file
                fi
        done done
+7  A: 

You mean, something along the line of:

find /path/to/files -name "artifact*" -type f -mtime +7 -exec rm {} \;

?

VonC
Thanks, that's a lot simpler than mine.
Feet
+1  A: 

If you trust the mtime of the file, you can do it in a simple sweep with find:

find "${NIGHTLY_LOCATIONS}" -name $ARTIFACT_PREFIX -type f -mtime +7 -delete
JesperE
Nice. VonC beat you to the punch, but I like -delete over "-exec rm {} \;", which I would've used, since I didn't know about -delete. Thanks!
Blair Conrad
-exec rm might be more portable, though.
JesperE