Reputation: 29
Ok, so what I'm trying to do is, all my backup folders are named dates 03-07-13. So I'm trying to select the day, and if it's greater than or equal to 7 days old, it will delete. This is what I have so far, but it's not working.
DATE=$(date +"%d")
for i in /media/backupdrive/*; do
DAY=${i:22:2}
if [ "$DAY" -ge "7" ]
then
echo "day greater than 7";
fi
done
the 22:2 cuts off the /media/backupdrive/00-
00 represents the month
Right now It's just checking if it's greater than 7, if it is, it prints it out.
EDIT: The problem was resolved. I want to thank you all for helping a bash beginner. Thank you again!
Upvotes: 0
Views: 222
Reputation: 792
Using the 'DAY' variable opens you up to "just rolled over" issues.
Some alternatives:
The time format I generally use incorporates the following:
[epoch seconds]-[YYYY][MM][DD]-[HH]:[MM]:[SS]
This lets you do things like asking for backups that are 7 days old from right now. You would do the math against the epoch seconds, which avoids the confusion of days rolling over.
Basically, the epoch seconds is for making time calcs easier. The other time stamp bits makes it human readable. The ordering makes it so that it sorts correctly in a folder listing.
EDIT:
In the event your backup path ever changes:
DAYtmp=${i: -8:5}
DAY=${DAYtmp: -2}
This will yield the DAY from the folder name if the parent paths change in length.
Upvotes: 0
Reputation: 40723
It seems you want to delete files that are older than 7 days. The find
command can find those files for you, and optionally delete them:
find /media/backupdrive -mtime +7 # Files that are older than 7 days
find /media/backupdrive -mtime +7 -delete # ... and delete them
Upvotes: 1
Reputation: 38436
Per a screenshot given in a comment, your actual code uses the following:
DAY=${i:22:2}
if [ "$day" -ge "7" ]
Emphasis on the capitalization-differences between DAY
and $day
. When this runs, it's trying to compare an empty-string to a string (or "numbers" via the -ge
) and this will cause the error you're receiving.
Try updating your if
statement to use the uppercase version:
if [ "$DAY" -ge "7" ]
Upvotes: 1