Monday 14 September 2015

Convert time Seconds to Hours-Minutes-Seconds format - Shell Scripting

Using below script you can convert the seconds to Hours-Minutes-Seconds.

Writing loop _hms then converting the hours / 3600 because for hour 3600 seconds. Minutes can be converted using 3600/60 because it's equal to Minute.

#!/bin/bash
##Author: Ankam Ravi Kumar
##Date: 14th, SEP, 2015
##Convert seconds to Hours:Minutes:Seconds Format using this Script
##  START ##

[ -z ${1} ] && echo "Usage: $(basename $0) <seconds>" && exit||secs=${1}
_hms()
{
 local S=${1}
 ((h=S/3600))
 ((m=S%3600/60))
 ((s=S%60))
 printf "%dh:%dm:%ds\n" $h $m $s
}

_hms ${secs}
## END ##


Execution steps:
~]$ ./seconds.sh
Usage: convert.sh <seconds>

~]$ ./seconds.sh 456
1h:0m:0s

The same script also can be write as one line base line like below

$ secs=3600
$ printf ""%dh:%dm:%ds"\n" $(($secs/3600)) $(($secs%3600/60)) $(($secs%60))

1h:0m:0s

Same conversion we can write using awk as below

$ echo - | awk -v "S=3600" '{printf "%dh:%dm:%ds",S/(60*60),S%(60*60)/60,S%60}'

1h:0m:0s 

Video Tutorial



 

No comments:

Post a Comment