Monday, December 6, 2010

How to get current time with milliseconds using Linux shell script

This is something I believe would be useful for many people when you want to, say, log data using linux shell script, or something alike.

The linux "date" command does have a parameter that gives current time in nanosecond accuracy, but not millisecond.  So what you want to do is to extract a substring from "date" output to convert the value into milliseconds.

filename="/tmp/tmpfile.log"

nanos=`date +%F-%T.%N`
echo -n "${nanos:0:23}" > $filename


Code above generates a timestamp in %Y-%m-%d-%H:%M:%S.mmm format and write into a file named /tmp/tmpfile.log.

${nanos:0:23} extracts the first 23 characters from the string generated by shell command "date +%F-%T.%N", where the parameter "%N" generates zero-filled nano-seconds of current time.

No comments:

Post a Comment