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 
1
  • I like VonC's answer, but just in case, is there a reason you can't rely on the filesystem date and must use the time embedded in the filename? Commented Oct 29, 2008 at 21:30

2 Answers 2

7

You mean, something along the line of:

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

?

Sign up to request clarification or add additional context in comments.

Comments

2

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 

2 Comments

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!
-exec rm might be more portable, though.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.