0

I have a bash script where I'm pulling the date from the last line of a text file, adding 1 day to the time and then writing that date back to the file. The idea is to add 24 hours each time. My code look like the following:

start_date=$(date -d "$(tail -n 1 run_dates.txt) +1 day" '+%F %T')
echo "$start_date" >> run_dates.txt

The output file (run_dates.txt) looks like this:

2018-09-18 16:42:57
2018-09-19 11:42:57
2018-09-20 06:42:57
2018-09-21 01:42:57
2018-09-21 20:42:57

For some reason it is only adding 19 hours every time, not a full day. Any idea what this is?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
intA
  • 2,513
  • 12
  • 41
  • 66
  • Possible duplicate of [How to increment a date in a bash script](https://stackoverflow.com/q/18706823/608639), [Adding days to GNU date command with time stamp](https://stackoverflow.com/q/50740879/608639), [Using date to get tomorrows date in Bash](https://stackoverflow.com/q/30235598/608639), [How to get the last month? date +%Y%m -d '1 month ago' doesn't work](https://stackoverflow.com/q/43113414/608639), etc – jww Sep 20 '18 at 02:00

2 Answers2

3

date's free-form date parser seems to get pretty confused with + something at the end of a date-time. All the gory details here: https://www.gnu.org/software/coreutils/manual/html_node/Date-input-formats.html

I get similar results:

$ tail -n 1 run_dates.txt
2018-09-21 20:42:57
$ date -d "$(tail -n 1 run_dates.txt) +1 day" '+%F %T'
2018-09-22 15:42:57

but if you ask for "tomorrow" instead of "+1 day":

$ date -d "$(tail -n 1 run_dates.txt) tomorrow" '+%F %T'
2018-09-22 20:42:57
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
0

For adding/subtracting interval to a date command don't use "+". If you omit + it adds, for subtraction you can use "ago" keyword along with the date part. Here are some examples

> date -d "2018-09-21 20:42:57 1 day 2 hours" "+%F %T"
2018-09-22 22:42:57
> date -d "2018-09-21 20:42:57 1 day ago 2 hours ago" "+%F %T"
2018-09-20 18:42:57
> date -d "2018-09-21 20:42:57 1 day 2 hours 12 minutes" "+%F %T"
2018-09-22 22:54:57
> date -d "2018-09-21 20:42:57 1 day 2 hours ago 12 minutes" "+%F %T"
2018-09-22 18:54:57
>
stack0114106
  • 8,534
  • 3
  • 13
  • 38