• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 595
  • Last Modified:

Compute 7 days ago in shell script

Hi, I have a simple backup script trigged by cron, below... it creates a backup file each day named for that day-- i.e. "db_01-03-2010.sql.bz2"

This works perfectly.

I want to ADD to this script so it computes the date for 7 days prior, and then removes that file-- so when "db_01-10-2010.sql.bz" is created, it'll figure out the date 7 days before (01-03-2010) and remove that file.

Obviously this is a hair non-trivial and I can't just subtract 7 from the day value, since the date 7 days before 01-03-2010 is 12-27-2009, etc.

How can I do this in a bash shell script?


mysqldump -u mysql_user -pmysql_pass tablename | bzip2 -c > /my/backups/db_`date +%m-%d-%Y`.sql.bz2

Open in new window

1 Solution
you can use find command to find the files 7 days older

find <path> -name *.* -mtime +7

if you have GNU date try this:

OLDDATE=$(date -d "7 days ago" "+%m-%d-%Y")
echo rm db_${OLDDATE}.sql.bz2

Of course you can write it as a one-liner:

echo rm db_$(date -d "7 days ago" "+%m-%d-%Y").sql.bz2

I put echo in front of the actual command, so you can verify if it will do what you desire.
Remove it when you're satisfied with the result.


pnoericAuthor Commented:
perfect, thank you.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now