I have a variable of $i which is seconds in a shell script, and I am trying to convert it to 24 HOUR HH:MM:SS. Is this possible in shell?
The command date +%S will print the current amount of seconds.
Sample shell script to display the current date and time #!/bin/bash now="$(date)" printf "Current date and time %s\n" "$now" now="$(date +'%d/%m/%Y')" printf "Current date in dd/mm/yyyy format %s\n" "$now" echo "Starting backup at $now, please wait..." # command to backup scripts goes here # ...
It is as easy as typing sleep N . This will pause your script for N seconds, with N being either a positive integer or a floating point number.
Here's a fun hacky way to do exactly what you are looking for =)
date -u -d @${i} +"%T"
Explanation:
date
utility allows you to specify a time, from string, in seconds since 1970-01-01 00:00:00 UTC, and output it in whatever format you specify.-u
option is to display UTC time, so it doesn't factor in timezone offsets (since start time from 1970 is in UTC)date
-specific (Linux): -d
part tells date
to accept the time information from string instead of using now
@${i}
part is how you tell date
that $i
is in seconds+"%T"
is for formatting your output. From the man date
page: %T time; same as %H:%M:%S
. Since we only care about the HH:MM:SS
part, this fits!Another approach: arithmetic
i=6789 ((sec=i%60, i/=60, min=i%60, hrs=i/60)) timestamp=$(printf "%d:%02d:%02d" $hrs $min $sec) echo $timestamp
produces 1:53:09
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With