Mostly Linux & Python syntax notes and hyperlinks.

Thursday, May 16, 2013

linux: a tenth of a second from ksh

We needed a time stamp of the format HHMMSST
where HH = hour, MM=minutes SS=seconds and T=one tenth of a second.

If you type "man time" you can see different format strings for days to seconds to nanoseconds:
 %j day of year (001..366)
 %k hour (0..23)
 %M minute (00..59)
 %S second (00..60); the 60 is necessary to accommodate a leap second
 %N nanoseconds (000000000..999999999)


To get the nanoseconds,  you can do

 N=$(date +%N)


This worked great in bash or korn shell.

To get the tenth of a second in the bash shell, it was simple to do: 


$ N=$(date +%N)
$ echo $N 
538595000 
$ t=${N:0:1} 
$ echo $t 


In the korn shell, I got this:

$ t=${N:0:1}
ksh: : bad substitution


I needed to generate the timestamp within an already-written ksh script.
I found two methods that worked in my korn shell script: using "expr" or using "typeset"

Using expr:

$ expr $N : '\(.\{3\}\)'
115
$ expr $N : '\(.\{1\}\)'
1

using typeset 

$ echo $N 
655762000 
$ typeset -L1 t=$N 
$ echo $t
6

I used typeset:

function set_timestamp 
{
    TOSEC=$(date +%H%M%S)
    NANO=$(date +%N)

    typeset -L1 TENTH=$NANO 

    TIMESTAMP=${TOSEC}${TENTH}


No comments:

Post a Comment