I want to generate a textual timestamp in the unix shell with microsecond accuracy, without using the %N date option (I am using busybox, a smaller unix toolset that does not have this option), to prefix to output I am generating. The timestamp should have the format "<seconds since epoc>.<microseconds>".

awk -f ./myawkscript.awk < /param | sed 's/$/\[<TIMESTAMP WOULD GO HERE>].'

So the desired output would look like:

[1305638345.123456] awk script output

I can obtain the epoc easy enough using date +"%s", so my question is, is there a way of obtaining the microseconds from the shell?

link|improve this question
feedback

2 Answers

#include <stdio.h>
#include <sys/time.h>
int main() {
    struct timeval t;
    struct timezone tz;

    if (gettimeofday(&t, &tz) == 0)
        printf("%d.%d\n", t.tv_sec, t.tv_usec);

    return 0;
}

Compile with cc -o timestamp timestamp.c

For completeness: clock_gettime() can return nanoseconds, but with an awk script you wouldn't reach that accuracy anyway.

link|improve this answer
feedback

Does busybox date accept the %N (nanoseconds) field?

time=$(date "+%s.%N")

To remove the "nano-ness"

time=$(date "+%s.%N" | cut -c 1-17)

or

time=$(date "+%s.%N"); time=${time%???}
link|improve this answer
To quote the question, "without using the %N date option (I am using busybox, a smaller unix toolset that does not have this option)" – grawity May 25 '11 at 6:05
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.