I'd like to know if there's a way to get the number of seconds since the UNIX epoch in any POSIX compliant shell, without resorting to non-POSIX languages like perl, or using non-POSIX extensions like GNU awk's strftime function.
Here are some solutions I've already ruled out...
date +%s
// Doesn't work on Solaris
I've seen some shell scripts suggested before, which parse the output of date
then derive seconds from the formatted gregorian calendar date, but they don't seem to take details like leap seconds into account.
GNU awk has the strftime
function, but this isn't available in standard awk
.
I could write a small C program which calls the time
function, but the binary would be specific to a particular architecture.
Is there a cross platform way to do this using only POSIX compliant tools?
I'm tempted to give up and accept a dependency on perl, which is at least widely deployed.
perl -e 'print time' // Cheating (non-POSIX), but should work on most platforms
Here is a portable / POSIX
solution:
PATH=`getconf PATH` awk 'BEGIN{srand();print srand()}'
Unlike a C
compiler or Perl
, awk
is guaranteed to be present on a POSIX compliant environment.
How it works:
PATH=`getconf PATH` is making sure the POSIX
version of awk
is called should it not be the first one in the PATH
.
Per the POSIX
standard :
srand([expr])
Set the seed value for rand to expr or use the time of day if expr is omitted. The previous seed value shall be returned.
The first call is omitting a parameter so the seed value is set to the time of day. The second call is returning that time of day, which is the number of seconds since the epoch.
Note that with many awk
implementations but not the GNU one (gawk
), this first call is not required as the function already returns the expected value in the first place.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With