Bash Shell 当前日期减去天数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14416914/
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
Bash Shell Current Date Minus Number of Days
提问by Jimmy
I am new to bash and shell but I am running a debian install and I am trying to make a script which can find a date in the past without having to install any additional packages. From tutorials I have got to this stage:
我是 bash 和 shell 的新手,但我正在运行 debian 安装,我正在尝试制作一个脚本,该脚本可以找到过去的日期,而无需安装任何其他软件包。从教程我已经到了这个阶段:
#!/bin/sh
#
# BACKUP DB TO S3
#
# VARIABLES
TYPE="DATABASE"
DAYS="30"
# GET CURRENT DATETIME
CURRENTDATE="$(date +%Y%m%d%H%M%S)"
# GENERATE PAST DATE FROM DAYS CONTSTANT
OLDERDATE=`expr $CURRENTDATE - $DAYS'
# CALL PYTHON SCRIPT WITH OLDERDATE ARGUMENT
python script.py $OLDERDATE
Where I am getting stuck is the fact that my "days" is just the number 30 and isnt datetime formattted, so when I come to minus it from the currentdate variable it obviously isnt compatible.
我卡住的地方是我的“天数”只是数字 30 并且不是日期时间格式,所以当我从 currentdate 变量中减去它时,它显然不兼容。
Would anyone be kind enough to help me find a way to get this working as it should?
有没有人愿意帮助我找到一种方法来让它正常工作?
回答by Michael Krelin - hacker
Try
尝试
date -d '30 days ago'
should do on debian.
应该在 debian 上做。
回答by Gilles Quenot
Try doing this :
尝试这样做:
#!/bin/sh
#
# BACKUP DB TO S3
#
# VARIABLES
TYPE="DATABASE"
DAYS="30"
# GET CURRENT DATETIME
CURRENTDATE="$(date +%Y%m%d%H%M%S)"
# GENERATE PAST DATE FROM DAYS CONSTANT
OLDERDATE="$(date "+%Y%m%d%H%M%S" -d "$DAYS days ago")"
# CALL PYTHON SCRIPT WITH OLDERDATE ARGUMENT
python script.py "$OLDERDATE"
See info coreutils 'date invocation' | less +/28.7\ Relative\ items\ in\ date\ strings
看 info coreutils 'date invocation' | less +/28.7\ Relative\ items\ in\ date\ strings
回答by viki
You can use the following script:
您可以使用以下脚本:
#!/bin/bash
days=73
while [ ${days} -ge 0 ]; do
date -d "${days} days ago" +'%F'
days=$((days-1))
done
回答by sendmoreinfo
You could modify the python script instead -- that way you would not depend on particular implementation of date
您可以改为修改 python 脚本——这样您就不会依赖于特定的实现 date