I was going through a tutorial and there I came across a command:
printf "%(%s)T"
The output of this command is:
1454299615
Could anybody please tell me what is this command and what the output means?
It's a way to express the formatted time by printf
.
The format is:
%(FORMAT)T
Where FORMAT
is defined by strftime(3)
.
So to get the epoch time (Time in seconds since 1970-01-01 00:00:00 UTC), we need strftime(3)
format %s
:
printf "%(%s)T\n"
Note that you also need \n
at the end to add a newline as printf
(unlike echo
) does not add it by default.
Example:
$ printf "%(%s)T\n"
1454300377
$ printf "%(%Y-%m-%d)T\n"
2016-02-01
$ printf "%(%Y-%m-%d %H:%M:%S)T\n"
2016-02-01 10:20:27
Just for the sake of completeness, you can also use date
command in a similar strftime(3)
formatted manner to get the time:
$ date '+%s'
1454300542
$ date '+%Y-%m-%d' ## Short form: date -I
2016-02-01
$ date '+%Y-%m-%d %H:%M:%S'
2016-02-01 10:22:47
NOTE: This behavior is specific to bash
's and ksh
's built-in function printf
, and doesn't work with /usr/bin/printf
, csh
, and zsh
built-ins.
printf(1)
man page.
Feb 1, 2016 at 15:36
printf
is a builtin here (although the external one has the same behavior)..check help printf
..
printf
a builtin?/usr/bin/printf
on Ubuntu 14.04 gives an error:printf: %(: invalid conversion specification
. If you're usingbash
. Tryman bash
for builtin documentation.