使用bash循环分钟和回显

时间:2016-10-17 13:35:27

标签: bash date

我想在一个月内迭代所有分钟(目的是生成CSV文件)。

但是当我尝试这个时:

d="2016-09-01 00:00:00"
 while [ "$d" != "2016-09-30 00:00:00" ]; do
 echo $d 
 d=$(date --utc "+%Y-%m-%d %H:%M:00" -d "$d + 1 minute" )
done

小时和分钟都在递增:

2016-09-01 00:00:00
2016-09-01 01:01:00
2016-09-01 02:02:00
2016-09-01 03:03:00
2016-09-01 04:04:00
2016-09-01 05:05:00
2016-09-01 06:06:00
2016-09-01 07:07:00
2016-09-01 08:08:00

我做错了什么以及如何正确地循环分钟?

3 个答案:

答案 0 :(得分:0)

我会使用Unix时间戳代替。

d=$(date --utc +%s -d "2016-09-01 00:00:00")
end=$(date --utc +%s -d "2016-09-30 00:00:00")
while [ "$d" != "$end" ]; do
    date --utc "+%Y-%m-%d %H:%M:00" -d "@$d"
    d=$(( d + 60 ))
done

答案 1 :(得分:0)

您可以在日期字符串变量package test; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.logging.Level; import java.util.logging.Logger; public class Test { public static void main(String[] args) { Runtime rt = Runtime.getRuntime(); try { // the query you want to run in mongo, you can get it // from a file using a FileReader String query = "db.col.find();"; // the database name you need to use String db = "database"; // run a command from terminal. this line is equivalent to // mongo database --eval "db.col.find()" // it calls the mongo binary and execute the javascript you // passed in eval parameter. It should work for both unix and // windows Process pr = rt.exec(new String[]{"mongo", db, "--eval", query}); // read the output of the command InputStream in = pr.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder out = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { out.append(line); } // print the command and close outputstream reader System.out.println(out.toString()); reader.close(); } catch (IOException ex) { Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex); } } } 之后添加时区 UTC以获得正确的输出:

$d

请注意在d="2016-09-01 00:00:00" for ((i=0; i<=60; i++)); do date --utc -d "$d UTC + $i minute" done Thu Sep 1 00:00:00 UTC 2016 Thu Sep 1 00:01:00 UTC 2016 Thu Sep 1 00:02:00 UTC 2016 Thu Sep 1 00:03:00 UTC 2016 Thu Sep 1 00:04:00 UTC 2016 Thu Sep 1 00:05:00 UTC 2016 ... ... Thu Sep 1 00:55:00 UTC 2016 Thu Sep 1 00:56:00 UTC 2016 Thu Sep 1 00:57:00 UTC 2016 Thu Sep 1 00:58:00 UTC 2016 Thu Sep 1 00:59:00 UTC 2016 Thu Sep 1 01:00:00 UTC 2016 后使用UTC

答案 2 :(得分:0)

在日期字符串中的时间组件之后使用+用于&#39; time zone correction&#39;不要做你想做的事。有趣的是,反转日期和时间是有效的:

$ date  "+%Y-%m-%d %H:%M:00" -d "21:31:00 2016-09-03 + 1 minute  "
2016-09-03 21:32:00

而另一种方式是混淆时区和偏移,所以结果可能取决于你的本地配置:

$ TZ=Europe/London date  "+%Y-%m-%d %H:%M:00" -d "2016-09-03 21:32:00 + 1 minute "
2016-09-03 21:33:00
$ TZ=Europe/Brussels date  "+%Y-%m-%d %H:%M:00" -d "2016-09-03 21:32:00 + 1 minute "
2016-09-03 22:33:00
$ TZ=Asia/Singapore date  "+%Y-%m-%d %H:%M:00" -d "2016-09-03 21:32:00 + 1 minute "
2016-09-04 04:33:00