brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: $EPOCHSECONDS and $EPOCHREALTIME give you the time without calling date

Shell
~/tips/tip-bash-epochseconds-epochrealtime

echo $EPOCHSECONDS

Two bash variables hold the current Unix time in seconds, or with microseconds.

For timestamps in a script I always typed $(date +%s). Bash has had two built-in variables for this for a while, and they save the extra process.

echo $EPOCHSECONDS
1796150520
echo $EPOCHREALTIME
1796150520.209257

The manual describes EPOCHSECONDS as the number of seconds since the Unix epoch, and EPOCHREALTIME as the same as a floating-point value with microsecond granularity. The value is looked up every time you reference the variable.

That makes a quick stopwatch easy:

s=$EPOCHREALTIME
sleep 0.3
e=$EPOCHREALTIME
echo $(( (${e/./} - ${s/./}) / 1000 )) ms
301 ms

Bash arithmetic can’t handle decimals, so ${e/./} removes the dot and leaves whole microseconds. Dividing by 1000 gives milliseconds. The 301 is what my run printed for a 0.3 second sleep.

Two caveats from the manual. Assignments to these variables are ignored: after EPOCHSECONDS=5 it still printed the real time. And if you unset either one, it loses its special behaviour, even if you set it again later, so don’t unset them in a script.

The dot trick assumes the value contains a dot, as it did here. Print $EPOCHREALTIME once where your script will run before you rely on it.

Further reading: Bash reference manual

More Shell tips zmv -n '(*).log' '$1.txt' zoxide query -ls project f=$(mktemp --suffix=.json) shopt globskipdots docker compose logs --tail 50 web # now at the top of a clean screen All Shell tips (78) All topics

Link