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

Viewed 705793

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

date doesn't seem to offer that option. Is there an easy way?

7 Answers

Pure bash solution

Since bash 5.0 (released on 7 Jan 2019) you can use the built-in variable EPOCHSECONDS.

$ echo $EPOCHSECONDS
1547624774

There is also EPOCHREALTIME which includes fractions of seconds.

$ echo $EPOCHREALTIME
1547624774.371210

EPOCHREALTIME can be converted to micro-seconds (μs) by removing the decimal point. This might be of interest when using bash's built-in arithmetic (( expression )) which can only handle integers.

$ echo ${EPOCHREALTIME/./}
1547624774371210

In all examples from above the printed time values are equal for better readability. In reality the time values would differ since each command takes a small amount of time to be executed.

Related