Compute 7 days ago in shell script

Posted on 2010-01-03
Last Modified: 2013-12-26
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 "" 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

Question by:pnoeric
    LVL 7

    Expert Comment

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

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

    Accepted Solution


    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.



    Author Closing Comment

    perfect, thank you.

    Featured Post

    How your wiki can always stay up-to-date

    Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
    - Increase transparency
    - Onboard new hires faster
    - Access from mobile/offline

    Join & Write a Comment

    How to remove superseded packages in windows w60 or w61 installation media (.wim) or online system to prevent unnecessary space. w60 means Windows Vista or Windows Server 2008. w61 means Windows 7 or Windows Server 2008 R2. There are various …
    Recently, an awarded photographer, Selina De Maeyer (, completed a photo shoot of a beautiful event ( in An…
    Learn several ways to interact with files and get file information from the bash shell. ls lists the contents of a directory: Using the -a flag displays hidden files: Using the -l flag formats the output in a long list: The file command gives us mor…
    Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…

    746 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    15 Experts available now in Live!

    Get 1:1 Help Now