Home > front end >  Mutual Exclusion bug subtracting dates
Mutual Exclusion bug subtracting dates

Time:05-14

I am trying to run bash code that errors when doing what I think is subtracting minutes from a date. There is an error that has to do with mutual exclusion that I can't find info about.

The code runs this command:

datestr=$(date -d -3 minutes -r IOP4/DSC_0041.JPG " %Y%m%d_%H%M")

When I run just date -r IOP4/DSC_0041.JPG " %Y%m%d_%H%M" I get the value: 20220217_2223 It seems thus that the issue I'm having is with the -d -3 minutes portion. Based on what I've read online I thought maybe the command would work if it was instead written:

datestr=$(date -d "-3 minutes" -r IOP4/DSC_0041.JPG " %Y%m%d_%H%M") or

datestr=$(date -d "-3 min" -r IOP4/DSC_0041.JPG " %Y%m%d_%H%M") or

datestr=$(date -d "now -3 minutes" -r IOP4/DSC_0041.JPG " %Y%m%d_%H%M"),

None of these work either; no matter what I get the error:

date: the options to specify dates for printing are mutually exclusive Try 'date --help' for more information.

CodePudding user response:

-dand -r both give date a reference value that's why it throws an error, there's a conflict. Unfortunately, man page does not mention they are mutually exclusive.

The reference date from the file can be passed to a second date command

dr=$(date -r myrouter-000.png --iso=seconds)
echo "${dr:0:10}_${dr:11:5}" | tr -d ':-'

20211028_2009

date -d "$(date -r myrouter-000.png --iso=seconds) -9 minutes" " %Y%m%d_%H%M"

20211028_2000

CodePudding user response:

The date command cannot do both a reference from a file and a date from a string together in a single command so you need to break them into separate commands. Also, if you know the number of minutes to reduce the date by, it's faster in cpu time, to just convert that to seconds (3 minutes = 180 seconds) and subtract it from a timestamp.

date -s "@$(($(date -r IOP4/DSC_0041.JPG " %s") - 180))" " %Y%m%d_%H%M"

Basically, the $(date -r IOP4/DSC_0041.JPG " %s") part gets the time of the file as a unix timestamp which is the number of seconds since Jan 1st, 1970. You can easily subtract 180 from that number $(($(date -r IOP4/DSC_0041.JPG " %s") - 180)) using a native bash built-in math function, and re-interpret (using the date -s "@[number] syntax) that back to whatever date format you prefer at the end of the statement. " %Y%m%d_%H%M"

  •  Tags:  
  • bash
  • Related