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.

##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}
 local S=${1}
 printf "%dh:%dm:%ds\n" $h $m $s

_hms ${secs}
## END ##

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

~]$ ./ 456

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))


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}'


Video Tutorial


No comments:

Post a Comment