Get seconds from the era in any POSIX compatible shell

I would like to know if there is a way to get the number of seconds since UNIX in any POSIX compatible shell without resorting to non-POSIX languages ​​like perl, or using non-POSIX extensions like GNU awk strftime function,

Here are some solutions that I have already ruled out ...

date +%s // Doesn't work on Solaris

I saw several shell scripts that analyze the output of date , then seconds are output from the formatted date of the gregorian calendar, but they do not seem to take into account data, such as seconds of a jump.

GNU awk has a strftime function, but this is not available in standard awk .

I could write a small C program that calls the time function, but the binary will be architecture specific.

Is there a cross-platform way to do this using only POSIX-compatible tools?

I am tempted to abandon and accept perl addiction, which is at least widely deployed.

perl -e 'print time' // Cheating (non-POSIX), but should work on most platforms

+4
source share
3 answers

Here is a portable / POSIX solution:

 PATH=`getconf PATH` awk 'BEGIN{srand();print srand()}' 

Unlike the C or Perl compiler, awk guaranteed to be present in a POSIX compatible environment.

How it works:

  • PATH = `getconf PATH` ensures that the POSIX awk version is invoked if it is not the first in PATH .

  • On POSIX standard : srand ([expression]) Set the initial value for rand to the expression or use the time of day if expr is omitted. The previous initial value must be returned.

    The first call omits the parameter, so the initial value is set to the time of day. The second call returns this time of day, which is the number of seconds since the era.

    Note that when using many awk implementations, but not in GNU one ( gawk ), this first call is not required, since the function already returns the expected value in the first place.

+8
source

Just for educational purposes, a little hack. But it's like POSIX, as you can imagine :-)

 #!/bin/sh : > x echo "ibase=8;$(pax -wx cpio x | cut -c 48-59)" | bc rm x 

Let's see what this prints:

 $ ./x.sh; date +%s 1314820066 1314820066 
+2
source

It should be portable enough, but requires write access to ${.CURDIR}; maybe it can be changed.

I did not use /tmp for the executable, since most people have /tmp installed noexec.

Works on FreeBSD, anyway.

 #!/bin/sh # Portably gets the date since epoch bn=`basename $0` prog=`mktemp /tmp/${bn}.mktime.XXXXXXX` || exit 1 >${prog}.c cat <<EOF #include <stdio.h> #include <time.h> int main() {printf("%ju", time(NULL)); return 0; } EOF cc ${prog}.c time=`./a.out` rm ${prog} a.out echo Time since epoch = $time seconds 
-3
source

Source: https://habr.com/ru/post/1304115/


All Articles