4

I would like to get the current timestamp of realtime clock in my BASH script. The hwclock command can print out the current time, but it is not timestamp.

I have considered parsing hwclock's output and then convert the results to a timestamp, but it seems the hwclock output will vary if the current locale gets changed. So if I give my script to my clients, they could use different locales than mine, and my parsing results could be wrong (and of course the timestamp will be wrong).

So my question is, what would be the best way to get timestamp from RTC? Thanks in advance.

Andrew Niefer
  • 4,279
  • 2
  • 19
  • 22
Xavier Young
  • 368
  • 3
  • 8
  • 1
    Your script can hard-code a locale; it doesn't have to use the one inherited from the environment. – chepner Apr 13 '16 at 16:06
  • Thanks chepner, that would be a solution, if there is no better way to do it :-) – Xavier Young Apr 14 '16 at 06:05
  • Why would you need a better solution? You don't have to set the locale globally, just for the command that parses the timestamp: `LOCALE=whatever parseTime`. – chepner Apr 14 '16 at 11:38

1 Answers1

2

When you call hwclock -D, you get an output like the following which contains the timestamp:

hwclock from util-linux 2.27.1
Using the /dev interface to the clock.
Assuming hardware clock is kept in UTC time.
Waiting for clock tick...
...got clock tick
Time read from Hardware Clock: 2018/09/27 09:03:46
Hw clock time : 2018/09/27 09:03:46 = 1538039026 seconds since 1969
Time since last adjustment is 1538039026 seconds
Calculated Hardware Clock drift is 0.000000 seconds
Thu 27 Sep 2018 11:03:45 CEST  .749554 seconds

The following command parses this output to extract the actual timestamp:

sudo hwclock -D | grep "Hw clock time" | sed "s/.* = \([0-9]\+\) seconds .*/\1/"
luator
  • 4,769
  • 3
  • 30
  • 51