如何在 Bash 的循环中增加日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11797805/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 02:55:51  来源:igfitidea点击:

How to increase a date within a loop in Bash

linuxbash

提问by JBoy

I'm working on this function that basically works on 2 dates. One is the current date, the other is a 1 month ago date. Heres the code:

我正在研究这个基本上适用于 2 个日期的函数。一个是当前日期,另一个是 1 个月前的日期。代码如下:

 dateTale=$(date -d "$(date) - 1 month" +%Y%m%d)
 now=$(date +%Y%m%d)
 while ["$dateTale" -lt "$now"]
  do 
   $dateTale=$(date -d "$dateTale + 1 day" +%Y%m%d) 
  echo "adding" 
 done

As you can see i'm trying to increase dateTale until it reaches the current date, buit i keep on getting the error message: [20120703: command not found I tried removing the quotes from within the while statement but still same error message. But even when resolved, will -lt calculate the actual date value or the numeric one?

正如您所看到的,我正在尝试增加 dateTale 直到它到达当前日期,但我不断收到错误消息:[20120703: command not found 我尝试从 while 语句中删除引号,但仍然是相同的错误消息。但即使解决了, -lt 会计算实际日期值还是数字值?

Any advice?

有什么建议吗?

回答by chepner

Spaces are important when using the [command:

使用[命令时空格很重要:

while [ "$dateTale" -lt "$now" ]

Also, you don't use the '$' when assigning to variables (unlike perl or php):

此外,在分配给变量时不要使用“$”(与 perl 或 php 不同):

dateTale=$(date -d "$dateTale + 1 day" +%Y%m%d)

回答by Michael Hoffman

Should be $dateTalenot $(dateTale).

应该$dateTale不是$(dateTale)

回答by Jay

#!/bin/sh

dateTale=$(date -d "$(date) - 1 month" +%Y%m%d)
now=$(date +%Y%m%d)


 while [ $dateTale -lt $now ]
  do
   dateTale=$(date -d "$dateTale + 1 day" +%Y%m%d)
  echo $dateTale
 done