Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash script, match on dates like?

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
like image 456
Feet Avatar asked Jan 22 '26 21:01

Feet


1 Answers

You mean, something along the line of:

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

?

like image 180
VonC Avatar answered Jan 24 '26 16:01

VonC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!