bash 如何在 Shell Scripting 中进行日期计算?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6417233/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to do date calculations in Shell Scripting?
提问by cfrederich
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?
我有一个每天晚上运行的 shell 脚本,用于将我的 EC2 站点数据库和 html 备份到 S3,当它备份文件夹时,它会在其中附加日期以便于查看。但我希望它也能够从 3 天前删除相关的备份文件夹。如何进行计算以获取 3 天前的日期?
#!/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)
回答by J.C. Yamokoski
You can use the -d flag for the date command:
您可以将 -d 标志用于 date 命令:
-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"`
回答by Kim Stebel
Why don't you use the modification time of the directories? Then you can just search for them with find. For exmaple:
为什么不使用目录的修改时间?然后你可以用 find 搜索它们。例如:
find backups -maxdepth 1 -mtime 3
回答by antonyh
It's different on BSD / Mac. You need to use the -voption:
它在 BSD / Mac 上有所不同。您需要使用该-v选项:
date -v -3d +%m%d%Y

