cfrederich
cfrederich

Reputation: 1790

How to do date calculations in Shell Scripting?

I have a shell script that runs every night to backup my EC2 sites database and html to S3, and when it backs the folders up, it appends the date to it for easier viewing. But I want it to also be able to delete the relevant backup folders from 3 days before. How can I do the calculations to get the date 3 days ago?

#!/bin/bash
DATE=`date +%m%d%Y`

s3cmd put -r /var/lib/mysql/mydb/ s3://mybucket/mydb-$DATE/
s3cmd put -r /home/ec2-user/public_html/ s3://mybucket/public_html-$DATE/
s3cmd del -r s3://mybucket/mydb-(date 3 days ago)

Upvotes: 8

Views: 13584

Answers (3)

Antony Hutchison
Antony Hutchison

Reputation: 2991

It's different on BSD / Mac. You need to use the -v option:

date -v -3d +%m%d%Y

Upvotes: 1

J.C. Yamokoski
J.C. Yamokoski

Reputation: 1014

You can use the -d flag for the date command:

-d, --date=STRING
     display time described by STRING, not 'now'

So, just change your date variable to:

DATE=`date +%m%d%Y -d "3 days ago"`

Upvotes: 13

Kim Stebel
Kim Stebel

Reputation: 42037

Why don't you use the modification time of the directories? Then you can just search for them with find. For exmaple:

find backups -maxdepth 1 -mtime 3

Upvotes: 3

Related Questions