Incrementing time (minutes and seconds) in bash / shell script
Note that this is Linux only. date -d
on BSD unixes (and possibly others) does something significantly different (and untoward).
You could use epoch time - i.e., seconds since 1 Jan 1970 00:00:00, for example:
#!/bin/bash
time=0
echo `date -d "1970-01-01 00:00:00 UTC $time seconds" +"%H:%M:%S"`
time=$((time + 600))
echo `date -d "1970-01-01 00:00:00 UTC $time seconds" +"%H:%M:%S"`
time=$((time + 600))
echo `date -d "1970-01-01 00:00:00 UTC $time seconds" +"%H:%M:%S"`
gives this output:
$ /tmp/datetest.sh
00:00:00
00:10:00
00:20:00
$
Related videos on Youtube
Comments
-
cbros2008 over 1 year
I need to increment minutes and seconds (in relation to time) in a variable.
First, I'm not sure whether declaring a 'time' variable is written as
time="00:00:00"
or
time=$(date +00:00:00)?
From there, I want to increment this variable by 10 minutes and seconds resulting in
01:00:00 increased to
01:10:10 to
01:20:20 etc (all the way up to midnight - 00:00:00)
What would be the best way to achieve this?I understand that doing
$ date -d "2010-07-07 200 days"
adds (200) days but I don't know how to apply this example to time (minutes and seconds) and not date?All replies are much appreciated.
-
Andrey Regentov over 9 years
+"%H:%M:%S"
is equivalent to%T
afair -
ghoti almost 6 yearsAlas, the
-d
option todate
does something completely different from what you intend in BSD unices and macOS. This solution is Linux-specific, even though the question was not. -
Chris J almost 6 years@ghoti - it's semi-implied by the question as he includes a -d example. However it's a fair point on the answer, I'll edit accordingly to make that clear.