Get current time in seconds since the Epoch on Linux, Bash

前端 未结 7 1516
长发绾君心
长发绾君心 2020-12-02 03:42

I need something simple like date, but in seconds since 1970 instead of the current date, hours, minutes, and seconds.

date doesn\'t seem t

7条回答
  •  半阙折子戏
    2020-12-02 03:58

    So far, all the answers use the external program date.

    Since Bash 4.2, printf has a new modifier %(dateformat)T that, when used with argument -1 outputs the current date with format given by dateformat, handled by strftime(3) (man 3 strftime for informations about the formats).

    So, for a pure Bash solution:

    printf '%(%s)T\n' -1
    

    or if you need to store the result in a variable var:

    printf -v var '%(%s)T' -1
    

    No external programs and no subshells!

    Since Bash 4.3, it's even possible to not specify the -1:

    printf -v var '%(%s)T'
    

    (but it might be wiser to always give the argument -1 nonetheless).

    If you use -2 as argument instead of -1, Bash will use the time the shell was started instead of the current date. This can be used to compute elapsed times

    $ printf -v beg '%(%s)T\n' -2
    $ printf -v now '%(%s)T\n' -1
    $ echo beg=$beg now=$now elapsed=$((now-beg))
    beg=1583949610 now=1583953032 elapsed=3422
    

提交回复
热议问题