Hi I have a bash script called by a systemd service that needs to run until the start of the next hour. Currently I have been using:
currentTime=$(date "%s")
nextHour=$(date -d "$(date -d 'next hour' ' %H:00:00')" ' %s')
duration=$(((nextHour-currentTime)*1000))
Which works except for trying to calculate the difference between 11pm and midnight were as far as I can tell it gets the current days midnight from 23 hours previous.
Oct 13 23:00:05 host bash[2019]: 1665698405
Oct 13 23:00:05 host bash[2019]: 1665615600
Oct 13 23:00:05 host bash[2019]: -82805000
I figure I could put a conditional check with a different calculation if needed or perhaps look at a systemd timer for triggering the service but as the service needs to always activate on boot/reboot as well as running hour to hour this setup seemed more appropriate.
Would appreciate any advice on why this is happening and advice on most streamlined steps to avoid it.
CodePudding user response:
This is happening because you're providing date
with a partial date string. Try with a full one:
nextHour=$(date -d "$(date -d 'next hour' %FT%H:00:00%:z)" %s)
CodePudding user response:
This isn't really a question about bash
, but seems to be more about date
. Given that date
has multiple different implementations, it seems wiser to choose a different tool to do the calculation. I suspect perl
is more standardized and (almost) as available as date
, so you might try to get the difference with:
perl -MTime::Seconds -MTime::Piece -E '
my $t = localtime; my $m = ($t ONE_HOUR)->truncate(to => "hour"); say $m - $t'