user2663468 user2663468 - 9 months ago 73
Bash Question

shell scripting time difference in variables

How can i get the time difference in 2 variables in shell

say i have 4 variables-

t1=07:50:19:612
t2=07:52:14:697
t3=10:20:54:201
t4=11:02:09:716

and i want to find difference in times
result=(t2-t1)+(t4-t3)

Answer Source

If milliseconds can't be ignored, I suggest you to define own shell functions :

function getMillis()
{
     val=($(echo $1|grep -Eo "(00|[1-9][0-9]*)"))
     mil=$(( ${val[0]} * 3600000 ))
     mil=$(($mil + ${val[1]}*60000))
     mil=$(($mil + ${val[2]}*1000))
     mil=$(($mil + ${val[3]}))
     echo $mil
} 

function format()
{
     hr=$(( $1 / 3600000 ))
     mn=$(( $1 % 3600000 / 60000 ))
     sc=$(( $1 % 60000 / 1000 ))
     ms=$(( $1 % 1000 ))
     echo "$hr hours,  $mn mins, $sc secs, $ms millisecs"
}

Then you can obtain the desired result as :

res=$(( $(getMillis $t2) - $(getMillis $t1) + $(getMillis $t4) - $(getMillis $t3) ))
format $res

The code above is just to show how this can be done. There may be other elegant solutions present.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download