0

I'm using a CentOS and I want to write a shell script. So

I have a file with a date:

> 
> cat VM1_EOMAP_TIME.log
07 Sep 2022 16:30
> 

And I want to get the minutes since current time and the date in the file

My idea is: ("EPOCH from current time" - "EPOCH from the date of that file") / 60

But I can't get the "EPOCH from current time"

> cat VM1_EOMAP_TIME.log
07 Sep 2022 16:30

> date --date='07 Sep 2022 16:30' +%s 1662568200

> date --date=$(cat VM1_EOMAP_TIME.log) +%s
date: extra operand ‘2022’ Try 'date --help' for more information.

> date --date=cat VM1_EOMAP_TIME.log +%s date: extra operand ‘2022’ Try 'date --help' for more information.

> TTT="07 Sep 2022 16:30" > echo $TTT 07 Sep 2022 16:30

> date --date=$TTT +%s date: extra operand ‘2022’ Try 'date --help' for more information.

Why I get "date: extra operand ‘2022’" error?

3 Answers3

1

If your bash is recent, the current time in epoch seconds is builtin: $EPOCHSECONDS

Otherwise, bash's printf can get it with the %(fmt)T directive and magic value "-1":

printf -v current_epoch '%(%s)T' -1

Also, bash has a builtin convenience for $(cat file) => $(<file):

log_epoch=$( date -d "$(<VM1_EOMAP_TIME.log)" "+%s" )
glenn jackman
  • 85,964
1

Your problem is quoting. And that you should use date -u to compensate for timezone.

$ echo "07 Sep 2022 16:30" > infile
$ var="$(<infile)"
$ cat infile; echo "$var"
07 Sep 2022 16:30
07 Sep 2022 16:30

$ date -ud "$(<infile)" ; date -ud "$var" +%s 1662568200 1662568200

$ varlog=$(date -ud "$var" +%s) #capture value for later

There are other simpler solutions in bash:

$ echo "$EPOCHSECONDS"; printf '%(%s)T' '-1'
1662582600
1662582600

$ var1="$EPOCHSECONDS"; printf -v var2 '%(%s)T' '-1' $ echo "$var1 $var2" 1662568200 1662568200

So, the final math could be:

$ echo $((var2 - varlog))
10747

$ echo $(((var2-varlog)/60)) 179

Related

  • Maybe the times are wall clock time, so the timezone is implied as that of the caller. Using -u might break that – Chris Davies Sep 07 '22 at 20:27
  • Well, the OP calculated the epoch to be 1662568200. If you reverse that date -ud @1662568200 +'%F %T %Z%z' you get back 2022-09-07 16:30:00 UTC+0000. Then, his computer is using UTC time (to match the time inside the file). But if his local time is New_York (for example) he would get: TZ="America/New_York" date -d @1662568200 +'%F %T %Z%z' --> 2022-09-07 12:30:00 EDT-0400. @roaima – QuartzCristal Sep 07 '22 at 21:23
  • So, it is better to use UTC times, or add a timezone to the value given to avoid guessing. @roaima – QuartzCristal Sep 07 '22 at 21:29
  • If the OP is converting based on UTC then UTC it should be. Good spot! – Chris Davies Sep 07 '22 at 22:30
  • 1
    See also date -f, if using GNU date. – Kusalananda Sep 08 '22 at 10:02
1
$ let diff=($(date +%s -d 'today')-$(date +%s -f VM1_EOMAP_TIME.log))/60
$ echo "$diff"
sseLtaH
  • 2,786