How to do date calculations in Shell Scripting?
Asked Answered
K

3

8

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)
Karonkaross answered 20/6, 2011 at 20:42 Comment(0)
G
13

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"`
Gemma answered 20/6, 2011 at 20:48 Comment(2)
Thanks! I thought I need to use awk or something.Caravaggio
And here is the list of recognized formats: gnu.org/software/coreutils/manual/html_node/…Prager
G
3

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
Gebhardt answered 20/6, 2011 at 20:47 Comment(1)
Very helpful!, use -mmin -60 to look for files modified within the last 60 minutes.Halter
B
1

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

date -v -3d +%m%d%Y
Belovo answered 17/10, 2018 at 11:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.