I'm looking at an instruction of the form:
$ printf [format] $elapsed
with $elapsed
expressed in seconds. I want it to output 'hh:mm:ss'. I couldn't figure out format
from the man. Would someone please make a suggestion?
I'm looking at an instruction of the form:
$ printf [format] $elapsed
with $elapsed
expressed in seconds. I want it to output 'hh:mm:ss'. I couldn't figure out format
from the man. Would someone please make a suggestion?
With the printf
builtin of the ksh93 shell, and assuming $elapsed
is less than 86400 (one day) that would be:
TZ=UTC0 printf '%(%T)T\n' "#$elapsed"
Or with the printf
builtin of recent versions of the bash shell (which has copied a subset of ksh93's feature in an incompatible way):
TZ=UTC0 printf '%(%T)T\n' "$elapsed"
%(strftime-format)T
is a ksh93 extension that consumes one argument which is interpreted as a timestamp and formats it as per the strftime()
format specification, where %T
short for %H:%M:%S
gives the time of day in HH:MM:SS 24-hour format. ksh93
handles all sorts of different timestamp formats including #number
for Unix epochtime while bash
handles only numbers which are interpreted as Unix epoch time except for -1
interpreted as now and -2
interpreted as the time the shell was invoked.
With the zsh
shell and its strftime
builtin:
zmodload zsh/datetime
TZ=UTC0 strftime %T $elapsed
With GNU or busybox date
:
date -ud "@$elapsed" +%T
Those basically interpret $elapsed
as an Unix epoch time, the number of Unix seconds since 1970-01-01 00:00:00 +0000, hence the TZ=UTC0
and -u
to get the corresponding UTC time on that January 1st 1970.
BTW, the man page you link to seems to try (and fail) to document a mix between the GNU printf
implementation and the printf
builtin of bash
, the GNU shell (two not fully compatible implementations of the standard printf
utility), I wouldn't trust that site.
Run man printf
on your system to get the man page of your standalone printf
utility¹, or info bash printf
or info zsh printf
or the man page of your shell if neither zsh nor bash for the documentation of its printf
builtin if it has one (most shells do).
¹ Beware though that if run from within the fish
shell, man printf
will give you the man page for fish's printf
builtin.
info bash printf
? – Stéphane Chazelas Mar 06 '23 at 08:59