Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 951
cfrederich Avatar asked Jun 20 '11 20:06

cfrederich


2 Answers

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"`
like image 177
J.C. Yamokoski Avatar answered Nov 16 '22 04:11

J.C. Yamokoski


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
like image 2
Kim Stebel Avatar answered Nov 16 '22 03:11

Kim Stebel