oxnz
oxnz

Reputation: 875

Is it possible to get a timestamp without invoking an external command like `date`?

zsh builtin print has option -P to perform prompt expansion, and this could be used to get the current time. I wonder if there are other ways to achieve this? And how about for other shells?

Upvotes: 6

Views: 284

Answers (1)

chepner
chepner

Reputation: 531215

bash 4.2 introduced a new format specifier for the printf builtin. With no argument, it prints the current time in the given format.

# Default is the current time
$ printf "%()T\n"
8:30 
# Current year
$ printf "%(%Y)T\n"
2015

An integer argument is treated as the number of seconds since Jan 1, 1970.

$ printf "%(%Y-%m-%d)T\n" 1234567890
2009-02-13

The same works in (some versions of) ksh, from which bash presumably borrowed it.

Upvotes: 8

Related Questions