0

I need a Bash script to accept 1 argument representing a time in hhmmss format, and from that derive a second time 3 minutes before that.

I've been trying to use date -d:

#! /bin/bash
DATE=`date +%Y%m%d`
TIME=$1
NEWTIME=`date -d "$DATE $TIME - 3 minutes" +%H%M%S`
echo $NEWTIME

In action:

$ ./myscript.sh 123456
invalid date `20141022 123456 - 3 minutes'

It seems the problem is with the 6 character time format because 4 characters (eg 1234) works. The subtraction of the 3 minutes is not the problem because I get the same error when I remove it.

It has occurred to me I could parse the time into a more palatable format before sending it to date. I tried inserting delimiters by adding this line:

TIME=${TIME:0:2}:${TIME:2:2}:${TIME:4:2}

It accepted that format but the answer to the - 3 minutes part was inexplicably very wrong (it subtracted 2 hours and 1 minute):

$ ./myscript.sh 123456
103356

Vexing.

It has also occurred to me that I might be able to provide date with an input format, like strptime which I'm familiar with from Python. I've found references to strptime in the context of Bash but I've been unable to get it to do anything.

Does anyone have any suggestions on getting the hhmmss time-string to work? Any help is much appreciated.

FYI: I'm trying to avoid changing the 6 character input format because that would involve changing other scripts as well as getting certain human users to alter long-entrenched habits. I'm also trying to avoid outsourcing this task to another language. (I could easily do this in Python). I want a Bash solution to this problem, if there is one.

ibonyun
  • 425
  • 3
  • 11
  • I think you hit on the correct answer with your delimiting. To get date to handle hhmmss time input it would seem you need to use hh:mm:ss but that hhmm is legal when "bare". The parsing oddity is certainly annoying and means you might need two calls to date for this. – Etan Reisner Oct 23 '14 at 00:03
  • The problem is with the `- 3 minutes` part. If I use your code that added the colons and leave that out, it works fine. – Barmar Oct 23 '14 at 00:09
  • @Barmar Interesting. But what is wrong with the `- 3 minutes` part? It complies fully with what is in the documentation, as far as I can tell. And it also works perfectly when given a time in hhmm format. – ibonyun Oct 23 '14 at 19:39
  • I don't know. It works when used by itself, but not when combined with a date and time. – Barmar Oct 23 '14 at 19:52

1 Answers1

3
TIME=093000
TIME=${TIME:0:2}:${TIME:2:2}:${TIME:4:2}         # your line
date -d "2014-10-20 $TIME 3 mins ago" +%H%M%S

Output:

092700
Cyrus
  • 84,225
  • 14
  • 89
  • 153